简体   繁体   中英

“[Error] ReferenceError: Can't find variable: data” when trying to get JSON data with AJAX / jQuery request

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.

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");
    }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM