Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

jquery - Cross domain ajax request to a json file using JSONP

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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#):

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?.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...