ajax响应:JSON数据后出现意外的非空白字符



我用jquery发送一个ajax请求,像这样:

$.post("ajax/myFile.php", {
myValue: "test"
}, function(response) {
console.log($.parseJSON(response))
})

myFile.php内容

myFunctionA();
myFunctionB();
function myFunctionA() {
echo json_encode(array('error' => 0, 'message' => "Hello World"));
}

function myFunctionB() {
echo json_encode(array('error' => 0, 'message' => "Hello again"));
}

my console.log result:

Uncaught SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 44 of the JSON data

我该如何处理这个?:/

您不能从脚本返回多个JSON值。您需要将它们组合成一个值。

echo json_encode([myFunctionA(), myFunctionB()]);
function myFunctionA() {
return array('error' => 0, 'message' => "Hello World");
}

function myFunctionB() {
return array('error' => 0, 'message' => "Hello again");
}

这将返回两个结果作为JavaScript中数组的元素。

最新更新