我在 PHP 中有一個字串,如下所示
$data = '{"post":{"fields":{"icon":{"height":768,"width":509,"url":"fetchdata16/images/d9/61/97/d96197470fc826c5a14e1f5c7497bcddd08ecf05f4c1b314360116650ab212e4.png","id":"fetchdata16/images/d9/61/97/d96197470fc826c5a14e1f5c7497bcddd08ecf05f4c1b314360116650ab212e4.png","format":"png"},"image":{"height":768,"width":509,"url":"fetchdata16/images/d9/61/97/d96197470fc826c5a14e1f5c7497bcddd08ecf05f4c1b314360116650ab212e4.png","id":"fetchdata16/images/d9/61/97/d96197470fc826c5a14e1f5c7497bcddd08ecf05f4c1b314360116650ab212e4.png","format":"png"},"title":"????? ????? ? ?????","hashtags":[{"title":"ViralLatest","id":""},{"title":"ViralThought For the DayLatest","id":""}]},"locations":[""],"language":"gu","type":"IMAGE","tags":{"dhTags":{"genre":["G300"],"subGenre":["SG326"]}},"ttl":{"id":"2","name":"Infinite","type":"NORMAL","value":"31536000"},"action":"submit","postId":null,"updatePublishedDate":false},"userId":33555}';
我正在嘗試使用 ajax 發送它,如下所示
<script>
var settings = {
"url": "https://example.com/update",
"method": "POST",
"timeout": 0,
"data": "<?php echo $data;?>",
"dataType": "json",
};
$.ajax(settings).done(function (response) {
console.log(response);
});
</script>
但它總是給我在控制臺中稱為資料的行上的屬性丟失錯誤。如果我使用如下資料
"data": "{\"post\":{\"fields\":{\"icon\":{\"height\":768,\"width\":509,\"url\":\"fetchdata16/images/d9/61/97/d96197470fc826c5a14e1f5c7497bcddd08ecf05f4c1b314360116650ab212e4.png\",\"id\":\"fetchdata16/images/d9/61/97/d96197470fc826c5a14e1f5c7497bcddd08ecf05f4c1b314360116650ab212e4.png\",\"format\":\"png\"},\"image\":{\"height\":768,\"width\":509,\"url\":\"fetchdata16/images/d9/61/97/d96197470fc826c5a14e1f5c7497bcddd08ecf05f4c1b314360116650ab212e4.png\",\"id\":\"fetchdata16/images/d9/61/97/d96197470fc826c5a14e1f5c7497bcddd08ecf05f4c1b314360116650ab212e4.png\",\"format\":\"png\"},\"title\":\"????? ????? ? ?????\",\"hashtags\":[{\"title\":\"ViralLatest\",\"id\":\"\"},{\"title\":\"ViralThought For the DayLatest\",\"id\":\"\"}]},\"locations\":[\"\"],\"language\":\"gu\",\"type\":\"IMAGE\",\"tags\":{\"dhTags\":{\"genre\":[\"G300\"],\"subGenre\":[\"SG326\"]}},\"ttl\":{\"id\":\"2\",\"name\":\"Infinite\",\"type\":\"NORMAL\",\"value\":\"31536000\"},\"action\":\"submit\",\"postId\":null,\"updatePublishedDate\":false},\"userId\":33555}",
它作業正常,但我不知道如何將我的 PHP 字串轉換為上述格式。如果有人幫助我解決難題,請告訴我。謝謝!
uj5u.com熱心網友回復:
不確定你是否真的需要一個字串。您可以簡單地創建一個物件并將其分配給您的資料變數。看起來你已經有了你需要的格式,所以你只需要洗掉你的引號
但是,如果您需要在 PHP 中將字串轉換為 JSON,您可以使用json_decode函式
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
如果要使用 JS 將字串轉換為 JSON,可以使用 JSON.stringify
<script>
var settings = {
"url": "https://example.com/update",
"method": "POST",
"timeout": 0,
"data": JSON.stringify("<?php echo $data;?>"),
"dataType": "json",
};
$.ajax(settings).done(function (response) {
console.log(response);
});
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/326309.html
標籤:javascript php 查询
