我有一段时间没有使用 JSON/PHP/AJAX,我很难访问返回的数据。我有一个 AJAX 函数,它调用一个 PHP 脚本,该脚本执行一个 API 调用,在$data. 该 JSON 通过解码$newJSON = json_decode($data);并循环创建一些存储在$cleanHTML. 然后我将变量$cleanHTML和原始$data变量放入一个新数组中$processedReturnArray = array($cleanHTML, $data);并对其echo json_encode($processedReturnArray); 进行编码以传递回 AJAX 脚本。我的问题:我假设对包含 JSON 字符串的数组进行 JSON 编码不是正确的方法。最好的解决方案是什么?这是我的 JS,您将看到我在哪里console.log以及$cleanHTML我看到的第一个元素,但是当我尝试从第二个对象记录值时,出现以下错误:Uncaught TypeError: Cannot read property 'results' of undefined jQuery(document).ready( function($) { $("#searchFormSubmit").click(function() { event.preventDefault(); console.log("In First Part of Search Submit!"); var address = $('#address').val(); $.ajax({ url : the_ajax_script.ajaxurl, type : 'post', data : { action : 'travel_app_ajaxdata', thangs : $('#CoreSearchForm').serialize() }, success : function( response ) { returnData = JSON.parse(response); console.log("This is my Clean HTML" + returnData[0]); console.log("This is my Location" + returnData[1]); console.log("TEST DATA - EVENT: " + returnData[1]["resultsPage"]); $('.return_data').html(returnData[0]);}, error: function(XMLHttpRequest, textStatus, errorThrown) { alert("Status: " + textStatus); alert("Error: " + errorThrown); } }); });});PHP 脚本由多个类组成,如果对解决方案有帮助,我可以发布一些内容。我还可以发布返回的 JSON 示例。
1 回答
UYOU
TA贡献1878条经验 获得超4个赞
试试这个,在处理请求的 php 代码中,将标头设置为 application/json。喜欢
header('Content-Type:application/json');
return json_encode($processedReturnArray);
- 1 回答
- 0 关注
- 136 浏览
添加回答
举报
0/150
提交
取消