[英]Why can't I pass a json array as data when doing GET request with jquery ajax?
[英]“[Error] ReferenceError: Can't find variable: data” when trying to get JSON data with AJAX / jQuery request
嘗試使用AJAX / jQuery請求獲取JSON數據時,出現錯誤“ [錯誤] ReferenceError:找不到變量:數據”。
我有一個index.html文件,它加載jQuery並嘗試從ajax.php文件中獲取數據。
index.html的內容
$.ajax({
url : 'ajax.php',
type : 'POST',
data : data,
dataType : 'json',
success : function (result) {
alert(result['ajax']);
},
error : function () {
alert("error");
}
});
ajax.php的內容
$someVariable = array(
'ajax' => 'Hello world!'
);
echo json_encode($someVariable);
通過瀏覽器訪問ajax.php可以正確顯示數據:
{"ajax":"Hello world!"}
我想念什么? 謝謝。
我不知道您要指的是哪個錯誤,但是我猜想您可以在成功回調中讀取json響應的響應,如果那樣的話,您將需要修改響應標頭
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
您尚未定義data
變量如果不發布任何數據,請嘗試以下操作:
$.ajax({
url : 'ajax.php',
type : 'POST',
dataType : 'json',
success : function (result) {
alert(result['ajax']);
},
error : function () {
alert("error");
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.