“[错误] ReferenceError:在尝试使用AJAX / jQuery请求获取JSON数据时找不到变量:data”

“[错误] ReferenceError:在尝试使用AJAX / jQuery请求获取JSON数据时找不到变量:data”

问题描述:

I am getting the error "[Error] ReferenceError: Can't find variable: data" when trying to get JSON data with AJAX / jQuery request.

I have an index.html file which loads jQuery and tries to get data from an ajax.php file.

CONTENT of index.html

$.ajax({
    url : 'ajax.php',
    type : 'POST',
    data : data,
    dataType : 'json',
    success : function (result) {
       alert(result['ajax']);
    },
    error : function () {
        alert("error");
    }
    });

CONTENT of ajax.php

$someVariable = array(
    'ajax' => 'Hello world!'
    );
echo json_encode($someVariable);

Accessing ajax.php through the browser displays the data correctly:

{"ajax":"Hello world!"}

What am I missing? Thanks.

我在尝试获取JSON时收到错误“[错误] ReferenceError:找不到变量:data” 使用AJAX / jQuery请求的数据。 p>

我有一个index.html文件,它加载jQuery并尝试从ajax.php文件中获取数据。 p>

index.html的内容 p>

  $ .ajax({
 url:'ajax.php',
 type:'POST',
 data:data,\  n dataType:'json',
 success:function(result){
 alert(result ['ajax']); 
},
错误:function(){
 alert(“error”); \  n} 
}); 
  code>  pre> 
 
 

ajax.php的内容 p>

  $ someVariable = array(
  'ajax'=>'Hello world!'
); 
echo json_encode($ someVariable); 
  code>  pre> 
 
 

通过浏览器访问ajax.php会显示数据 正确: p>

  {“ajax”:“Hello world!”} 
  code>  pre> 
 
 

我缺少什么? 谢谢。 p> div>

I dont know which error you are refering to, but I'm guessing you are enable to read the response of your json response in the success callback, if thats the case you will need to modify the response headers

$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);

You haven't defined data variable If you not post any data try this:

$.ajax({
    url : 'ajax.php',
    type : 'POST',
    dataType : 'json',
    success : function (result) {
       alert(result['ajax']);
    },
    error : function () {
        alert("error");
    }
    });