首页 > 解决方案 > 使用 PHP 将 Json 字符串加载到 Ajax

问题描述

我在 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 字符串转换为上述格式。让我知道是否有人帮助我解决难题。谢谢!

标签: javascriptphpjquery

解决方案


不确定你是否真的需要一个字符串。您可以简单地创建一个对象并将其分配给您的数据变量。看起来你已经有了你需要的格式,所以你只需要删除你的引号

但是,如果您需要在 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>

推荐阅读