简体   繁体   中英

Processing data from an AJAX request

I have a PHP API I'm working with that outputs everything as JSON.

I need to call one of the API methods and parse it out using an AJAX request. I am using jQuery (though it shouldn't matter).

When I make the request it errors out with a "parsererror" as the textStatus and a "Syntax Error: invalid label" when I make the request.

Simplified code:

$.ajax
({
    type: "POST",
    url: "http://mydomain.com/api/get/userlist/"+mid,
    dataType: "json",
    dataFilter: function(data, type)
    {
        /* Here we assume and pray */
        users = eval(data);
        alert(users[1].id);
    },
    success: function(data, textStatus, XMLHttpRequest)
    {
        alert(data.length); // Should be an array, yet is undefined.
    },
    error: function(XMLHttpRequest, textStatus, errorThrown)
    {
        alert(textStatus);
        alert(errorThrown);
    },
    complete: function(XMLHttpRequest, textStatus)
    {
        alert("Done");
    }
});

If I leave off the eval(data) then everything works fine. Well, except for data still being undefined in success . Note that I'm taking an array of objects in PHP and then passing them out through json_encode . Would that make any difference?

There has been no progress made on this. I'm willing to throw more code up if someone believes they can help.

Here is the PHP side of things

private function _get_user_colors($id)
{
    $u = new User();
    $u->get_where(array('id' => $id));

    $bar = array();

    $bar['user'] = $u->stored;

    foreach($user->colors as $color)
    {
        $bar['colors'][] = $color;
    }

    echo(json_encode($bar));
}

I have had zero issues using this with other PHP based scripts. I don't know why Javascript would take issue with it.

Parsererror generally indicates that the response from the server is malformed. If you load it directly in a browser does it look good?

Try outputting alert(request.responseText) (and rename the first argument to request ) in your error handler. That should fix you up with the errorsome output of your script.

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