AJAX 调用并清理 JSON 但语法错误:丢失;声明前 [英] AJAX call and clean JSON but Syntax Error: missing ; before statement

查看:22
本文介绍了AJAX 调用并清理 JSON 但语法错误:丢失;声明前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码进行跨域 JSONP 调用:

I am making a cross domain JSONP call using this code:

jQuery.ajax({
        async: true,
        url: 'http://mnews.hostoi.com/test.json',
        dataType: 'jsonp',
        method: "GET",
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(textStatus + ': ' + errorThrown);
        },
        success: function (data, textStatus, jqXHR) {
            if (data.Error || data.Response) {
                exists = 0;
            }
        }
    });

在 Firebug 中调试时,出现以下错误:

When debugging in Firebug, I get the following error:

SyntaxError: missing ; before statement

但是,当我通过 jsonlint.com 之类的工具传递我的 json 对象(可通过 JQ 代码中的链接获得)时,它说它是有效的 JSON.而且我也没有发现任何异常.它怎么会返回一个语法错误?是我没有得到一些 JSONP 细节还是什么?

However, when I pass my json object (available through the link in the JQ code) through a tool like jsonlint.com, it says it is valid JSON. And I don't find any anomalies either. How could it be returning a syntax error? Is it some JSONP detail I am not getting or what?

{"news":[ {
  "sentences": [
    "Neuroscientists have discovered abnormal neural activity...", 
    "The researchers found that these mice showed many symptoms...", 
    ""Therefore," the study authors say, "our findings provide a novel.."
  ], 
  "summaryId": "ZJEmY5", 
  "title": "Abnormal neural activity linked to schizophrenia"
}]}

提前致谢.

推荐答案

JSONP 不是 JSON.一个 JSONP 响应将由一个 JavaScript 脚本组成,该脚本只包含一个函数调用(到一个预定义的函数)和一个参数(这是一个符合 JSON 语法的 JavaScript 对象文字).

JSONP is not JSON. A JSONP response would consist of a JavaScript script containing only a function call (to a pre-defined function) with one argument (which is a JavaScript object literal conforming to JSON syntax).

您得到的响应是 JSON,而不是 JSONP,因此您在 JSONP 失败时处理它的努力失败了.

The response you are getting is JSON, not JSONP so your efforts to handle it as JSONP fail.

dataType: 'jsonp' 更改为 dataType: 'json' (或完全删除该行,服务器发出正确的内容类型,因此您不需要覆盖它).

Change dataType: 'jsonp' to dataType: 'json' (or remove the line entirely, the server issues the correct content-type so you don't need to override it).

由于您的脚本在与 JSON 不同的来源上运行,因此您还需要 采取措施(大多数,但不是全部,其中要求您控制提供 JSON 的主机)来解决 同源策略.

Since your script is running on a different origin to the JSON then you will also need to take steps (most, but not all, of which require that you control the host serving the JSON) to work around the same origin policy.

这篇关于AJAX 调用并清理 JSON 但语法错误:丢失;声明前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆