【问题标题】:Removing the first line from a JSON response从 JSON 响应中删除第一行
【发布时间】:2014-08-08 01:02:31
【问题描述】:

我当前的代码是:

$.getJSON("https://www.domain.com/someapi/callback=?",
    function(data){
      $.each(data, function(i,item){            
        alert(item.x);
      });
  });

现在我收到一个错误,因为他们在我的 json 响应的顶部添加了一行。有没有办法摆脱那条线?

谢谢!

更新:

我也尝试过这样做:

$.ajax({
    url: "https://www.domain.com/someapi/callback=?",
    type: "get",
    success: function (data) {
        alert(data)
    }
});

但这是一个跨域调用,所以我得到了那个错误。

【问题讨论】:

  • $.getJSON 需要一个有效的 json。您必须发出正常请求,获取文本,剪切第一行,然后将其解析为 json。
  • 好的,但是我如何正常进行跨域请求?查看我的更新。
  • 那行是什么?服务器返回什么?
  • 'allowIllegalResourceCall 为假。'这是为了保护 api 免受非法内容的侵害 :)
  • 在进行 ajax 调用时将 crossDomain 设置为 true 并将 dataType 设置为 jsonp 以及其他属性。另请参阅:stackoverflow.com/questions/3506208/jquery-ajax-cross-domain

标签: javascript jquery ajax json


【解决方案1】:

发出ajax普通请求

$.ajax({
    url : "https://www.domain.com/someapi/callback=?",
    success : function(result){
        // So here we get the result json with an error
        // So lets say the response is something like this
        /*
            There was an error on line 35
            {
                json : true
            }
        */
        // So we remove everything before the first '{'
        result = result.replace(/[^{]*/i,'');
        //We parse the json
        var data = JSON.parse(result);
        // And continue like no error ever happened
        $.each(data, function(i,item){            
            alert(item.x);
        });
    }
});

我希望这行得通。 (必须从服务器启用跨域请求)

【讨论】:

  • 我无法从服务器端启用跨域请求。
  • 如果您能够制作 $.getJSON 且未出现跨域错误,则此功能已启用。如果它没有被禁用,它可能是为了不进行跨域请求。这是一个安全问题。
  • 我可以使用带有回调的 jsonp 或 .getJSON 进行调用,但他们会在 json 中添加一行以确保没有任何自动爬虫或网络钓鱼者在外面寻找数据。跨度>
  • 如果 getJSON 有效,我给你的代码可能也会有效。但请记住,您试图“爬行”,而这正是他们试图阻止的。
猜你喜欢
  • 2017-04-24
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多