dongying6896
dongying6896
2014-11-25 23:59

“[错误] 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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dtup3446 dtup3446 7年前

    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);
    
    点赞 评论 复制链接分享
  • dsfsdf5646 dsfsdf5646 7年前

    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");
        }
        });
    
    点赞 评论 复制链接分享