Same Origin Policy Error when using jQuery JSONP with CloudFlare API

天大地大妈咪最大 提交于 2019-12-11 11:58:10

问题


I recieve an error (XMLHttpRequest cannot load https:// www.cloudflare.com/api_json.html?tkn=&email=&z=&a=rec_load_all&callback=%3F. Origin http:// domainmanager.tech-bytes.org is not allowed by Access-Control-Allow-Origin.) (spaces inserted in URLs due to Stack Overflow link limit) when trying to send a JSONP request via jQuery to CloudFlare. The CloudFlare API states that you can ask for a JSONP callback by appending a &callback=mycallback parameter. I am not sure if I am supposed to replace mycallback with something, I tried replacing it with ? as that is what some other resources said, or if I have to do some other modifications to my code.


回答1:


Try in this way for cross domain request.

  $.ajax({ url: "yourUrl",
    data:{paramName1: JSON.stringify(paramValue1),paramName2: JSON.stringify(paramValue2)},

        contentType: "application/json; charset=utf-8",
       dataType: "jsonp",
      success: function(data) {
          alert(data.d);
       },
       error: function(XMLHttpRequest, textStatus, errorThrown) {
           alert(textStatus);
       }
    });



回答2:


You can use CORS for this purpose.

Example code:

jQuery.support.cors = true; 

function CrosDom_ajax(url) {
        if (window.XDomainRequest
        && $.browser.msie
        && $.browser.version < 10) {
        xdr = new XDomainRequest();
        if (xdr) {
            xdr.onload = function () {
               alert(xdr.responseText);

            };
            xdr.open("get", url);
            xdr.send();
        }
        }
        else {
            $.ajax({
                url: url,
                success: function (response) {


                },
                error: function (data) {
                }
            });
         }
    }

Also you need to Write the following code in server side, to allow cross domain access

Response.AppendHeader("Access-Control-Allow-Origin", "*");           


来源:https://stackoverflow.com/questions/15104981/same-origin-policy-error-when-using-jquery-jsonp-with-cloudflare-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!