简体   繁体   English

处理来自AJAX请求的数据

[英]Processing data from an AJAX request

I have a PHP API I'm working with that outputs everything as JSON. 我有一个PHP API,正在使用该API将所有内容输出为JSON。

I need to call one of the API methods and parse it out using an AJAX request. 我需要调用一种API方法,并使用AJAX请求将其解析出来。 I am using jQuery (though it shouldn't matter). 我正在使用jQuery(尽管没关系)。

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. 当我发出请求时,发出错误时会显示“ parsererror”作为textStatus和“语法错误:无效标签”。

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. 如果我不使用eval(data)那么一切正常。 Well, except for data still being undefined in success . 好吧,除了data仍未success定义之外。 Note that I'm taking an array of objects in PHP and then passing them out through json_encode . 请注意,我在PHP中获取一个对象数组,然后将它们通过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 这是PHP的一面

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. 与其他基于PHP的脚本一起使用时,我的问题为零 I don't know why Javascript would take issue with it. 我不知道为什么Javascript会对此提出质疑。

Parsererror generally indicates that the response from the server is malformed. Parsererror通常指示来自服务器的响应格式错误。 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. 尝试在错误处理程序中输出alert(request.responseText) (并将第一个参数重命名为request )。 That should fix you up with the errorsome output of your script. 那应该可以解决脚本输出错误的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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