跨域Ajax请求使用JSONP的JSON文件 [英] Cross domain ajax request to a json file using JSONP

查看:572
本文介绍了跨域Ajax请求使用JSONP的JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要访问一个JSON文件,该文件位于域(example.com)由域2(example2.com)。例如,

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

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

我想使这个Ajax请求example.com从其他域(即)example2.com。

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

我已经试过JSONP。我不明白它是如何工作的。有人可以解释的方式开展工作?

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

推荐答案

您的服务已返回JSONP,这基本上是JavaScript的code。 你需要从你的Ajax请求提供一个回调函数来服务,并返回的功能是什么电话。

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.

下面是一个工作的例子。

Below is a working example.

Ajax请求:

$.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'
        });

服务器端code返回JSONP(C#):

server side code returning 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();
    }

什么是JSONP一回事?。

这篇关于跨域Ajax请求使用JSONP的JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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