Cross domain ajax request to a json file using JSONP

后端 未结 2 1362
庸人自扰
庸人自扰 2020-12-06 03:39

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         


        
相关标签:
2条回答
  • 2020-12-06 04:14

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

    0 讨论(0)
  • 2020-12-06 04:24

    Have you tried calling it as:

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

    And see what happens?

    0 讨论(0)
提交回复
热议问题