2013-05-29 95 views
0

由于API只有xml,所以ajax请求dataType必须以xml形式发送。我正在使用插件脚本来让我绕过跨域问题。脚本在下面找到。
由于使用了插件,响应以json的形式返回。Jquery AJAX Json响应数据未在浏览器中显示

我不知道为什么我无法获得个人响应数据显示。我设法显示的唯一东西是浏览器中的[object object]。

https://github.com/denka/jQuery-Plugins/blob/e5f123741ce6bc1be93e1db846a0e59cfe7e750c/cross-domain-ajax/jquery.xdomainajax.js

为了得到这个工作的任何建议,将不胜感激。

$.ajax({ 
    url: 'http://api.smartpea.com/api/deal/?title=water&zip=90210, ///URL + User Input 
    dataType: 'xml', 
    type: 'get', 
    beforeSend: function(){// Before Send, Add the Loader 
    $("#loading").show(); 
    }, 
    complete: function(){// Once Request is complete, Remove the Loader 
    $("#loading").hide(); 
    }, 
    success: function(data){ 
     var placement = document.getElementById('content');// location to where response is to be displayed to the user 

     jQuery.parseJSON(data); parse the json response 
     $.each(data, function(i) { 

     placement.innerHTML = data[i].Title, data[i]. BrandName, data[i]. CurrentPrice, data[i].Category; //adding the response data to the content holder in the browser 
     });  
    }, 
    error: function (xhr, ajaxOptions, thrownError){// Error Logger 
    console.log(xhr, ajaxOptions, thrownError); 
    } 

}); 
+0

'placement.innerHTML = ...'行是无效的 - 不知道你要去那里,但你的逗号分隔值会给出一个javascript错误。 –

+0

我是一个Jquery的新手,我不知道如何才能将这些项目从json响应传递到我的内容div。我也尝试将它们附加到它,但也没有解决。 –

+0

如果您的回复是XML,并且您正在调用'parseJSON',它肯定会炸毁。 –

回答

0

你sucess功能可能是这样

success: function(data){ 
      jQuery.parseJSON(data); parse the json response 
      $.each(data, function(i) { 
      $('#content').html(data[i].Title+','+data[i]. BrandName+','+data[i]. CurrentPrice+','+data[i].Category) 

      });  
     } 
0
$.ajax({ 
    url: 'http://api.smartpea.com/api/deal/?title=water&zip=90210', 
    dataType: 'xml', 
    type: 'get', 
    beforeSend: function(){ 
    $("#loading").show(); 
    }, 
    complete: function(){ 
    $("#loading").hide(); 
    }, 
    success: function(data){ 
     var placement = document.getElementById('content'); 

     jQuery.parseJSON(data); parse the json response 
     $.each(data, function(i) { 
     placement.innerHTML = data[i].Title + " - " + data[i].BrandName + " - " + data[i].CurrentPrice + " - " + data[i].Category; 
     });  
    }, 
    error: function (xhr, ajaxOptions, thrownError){ 
    console.log(xhr, ajaxOptions, thrownError); 
    } 
}); 
+0

它似乎工作,但数据项显示为未定义 - 未定义 - 未定义 - 未定义。 –

+0

这是我的请求结果的一个pastebin。 http://pastebin.com/FMHaUeVt 我仍然不确定为什么一切都显示为未定义。我一直在使用的验证工具显示返回的json是有效的,但它带有很多额外的东西。 jsonformatter.curiousconcept.com –

+0

这个json是无效的 –

1

最明显的错误是在第二行的URL的末尾缺少引号。你应该考虑在你的代码上使用JSHint

+0

你可以提供一些理由为什么OP应该考虑使用JSHint吗? – DeanOC

+0

除了捕捉示例中的基本错误之外,它还有助于强化良好的JS风格和语法。 – Fallexe