jQuery 使用 JSONP 跨域 ajax 请求到 json 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19489976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:05:46  来源:igfitidea点击:

Cross domain ajax request to a json file using JSONP

jqueryajaxjsonjsonp

提问by vigneshmoha

I want to access a JSON file which is in domain1 (example.com) from domain2 (example2.com). For example,

我想从 domain2 (example2.com) 访问 domain1 (example.com) 中的 JSON 文件。例如,

$.ajax({
    type:'get',
    url: 'http://example.com/vigneshmoha.json',
    success: function(data) {
        console.log(data);
    },
    statusCode: {
        404: function() {
            console.log('Status code: 404');
        }
    }
}); 

I want to make this ajax request to example.com from some other domain (ie) example2.com.

我想从其他域(即 example2.com)向 example.com 发出这个 ajax 请求。

I have tried JSONP. I couldn't understand how it works. Can someone please explain the way its work?

我试过 JSONP。我无法理解它是如何工作的。有人可以解释一下它的工作方式吗?

回答by Saranya

Your service has to return jsonp, which is basically javascript code. You need to supply a callback function to the service from your ajax request, and what is returned is the function call.

您的服务必须返回 jsonp,它基本上是 javascript 代码。你需要从你的ajax请求中向服务提供一个回调函数,返回的是函数调用。

Below is a working example.

下面是一个工作示例。

ajax request:

阿贾克斯请求:

$.ajax({
            crossDomain: true,
            type:"GET",
            contentType: "application/json; charset=utf-8",
            async:false,
            url: "http://<your service url here>/HelloWorld?callback=?",
            data: {projectID:1},
            dataType: "jsonp",                
            jsonpCallback: 'fnsuccesscallback'
        });

server side code returning jsonp (c#):

返回 jsonp (c#) 的服务器端代码:

public void HelloWorld(int projectID,string callback)
    {

        String s = "Hello World !!";
        StringBuilder sb = new StringBuilder();
        JavaScriptSerializer js = new JavaScriptSerializer();
        sb.Append(callback + "(");
        sb.Append(js.Serialize(s));
        sb.Append(");");
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";
        Context.Response.Write(sb.ToString());
        Context.Response.End();
    }

Refer What is JSONP all about?.

请参阅什么是 JSONP?.

回答by napo

Have you tried calling it as:

您是否尝试将其称为:

$.getJSON('http://example.com/vigneshmoha.json?callback=foo', null, function(data) {
          console.log(data);
});

And see what happens?

看看会发生什么?