使用JavaScript解析JSON。来自Laravel的JSON

3
我正在使用Laravel来查询Google的搜索API。以下是执行此操作的代码:
Route::get('google/(:any)', function($query)
{
    $uri = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=".$query;
    $response = Httpful::get($uri)->send();
    $r = json_decode($response); 
    return Response::json($r);
});

这可以通过http://example.com/w/google/queryhere访问。

我也试图在JavaScript中进行多个请求并解析JSON。

$.when( $.ajax(google), $.ajax(bing), $.ajax(yahoo)).then(function(resp1, resp2, resp3)
{ 
    var obj = jQuery.parseJSON(resp1);
});

然而,在使用parseJSON方法时,我得到了一个意外的语法标记。我不知道哪里出错了。


4
你能提供你所获取的JSON响应吗? - John x
1个回答

2
首先,$.ajax 会自动解析 JSON 响应,不需要手动处理。
其次,$.when 应用于返回多个参数的 promise 时有些晦涩。通常,对于 ajax deferred 的回调函数有 3 个参数:data, textStatus, jqXHR。但是,合并的 promise 将以数组形式(每个 deferred 对应一个数组)解析它们。
因此,请将代码更改为:
$.when( $.ajax(google), $.ajax(bing), $.ajax(yahoo)).then(function(resp1, resp2, resp3){ 
    var obj = resp1[0];
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接