Make ajax call cross domain

北战南征 提交于 2019-12-11 16:28:40

问题


I have an ajax call I would like to become cross domain how can I do this? The script is below

$.ajax({
        type: "GET",
        url: url,
        data: {sendername: sendername, email: email, subject: subject, message: message},
        dataType: "jsonp",
        crossDomain: "true",
        success: function (data) {
            if (data == 'success') {
                // show thank you remember to add a dialog inside
                $contactpage.find('.contact-thankyou').show();
                $contactpage.find('.contact-form').hide();
            }  else {
                alert('Unable to send your message. Please try again.'); //remember to add a dialog inside
            }
        }
    });

The url returns the following echo json_encode($result); the value of $result can be success if successful and anything else if unsuccessful.

the PHP ends with this echo $_GET['callback']."(".json_encode($result).");";


回答1:


You can request and get jsonp ONLY IF the web service you are hitting is set up for cross domain access, so your ajax call has to be right and the webservice has to be right.

ajax call

            $.ajax({
            type: "GET",
            cache: false,
            dataType: 'jsonp',
            // we are setting base_url at the top, like http://www.MyDomain.com/MyPage.svc/
            url: base_url + "GetGfeQuote?strJsonRequestObject=" + JSON.stringify(LoadedGetQuoteObject()),
            contentType: "text/plain",
            success: function (theJson) {
                // I make sure I got json
                if (theJson.indexOf('{') > -1 ) {
                    glb_the_quote = $.parseJSON(theJson);
                    if (glb_the_quote.errorMessage.length == 0) {
                        PopulateResultsPage();                            
                    } else {
                        alert('There was an error getting the quote: ' + glb_the_quote.errorMessage);
                    }
                } else {
                    alert(theJson)
                }
            },
            error: function (req, status, error) {
                if(status == "timeout"){
                    ShowNoInternetConnectionWarning();
                } else {
                    alert("There was an internet error = " + status + ", " + error);
                }
            },
            // this gives the webservice 7 seconds to return
            timeout: 7000
        });
        // end ajax;

Now the webservice: At one point it seemed that I had to have a web config, configured correctly, in the same dir as the webservice code - the .svc file - so that is what I do.

This is all I put in my svc file:

<%@ ServiceHost Language="C#" Factory="System.ServiceModel.Activation.WebServiceHostFactory"  Debug="true" Service="gfeWebService.ws.wsGfe" CodeBehind="wsGfe.svc.cs" %>

And the webconfig has to have stuff like the following (note crossDomainScriptAccessEnabled="true" )

<system.serviceModel>   
            <behaviors>
                    <endpointBehaviors>
                        <behavior name="webHttpBehavior">
                            <webHttp />
                        </behavior>
                    </endpointBehaviors>
                </behaviors>

                <bindings>
                    <webHttpBinding>
                        <binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />
                    </webHttpBinding>
                </bindings>

                <!-- the names have to be fully qualified. If you get an error that says, I can't find blah blah, you don't have the names right -->
                <services>
                    <service name="gfeWebService.ws.wsGfe"> 
                        <endpoint  address=""
                                   binding="webHttpBinding"
                                   bindingConfiguration="webHttpBindingWithJsonP"
                                   contract="gfeWebService.ws.IwsGfe"
                                   behaviorConfiguration="webHttpBehavior"
                        >
                        </endpoint>
                    </service>
                </services>

</system.serviceModel>

Tips

  • put a break point in you js code near the url: line, grab the value that is ending up in url: ... in other words, grab how this resolves

    base_url + "GetGfeQuote?strJsonRequestObject=" + JSON.stringify(LoadedGetQuoteObject())

and paste it in the address box of your browser. You get a more meaningful error message that way.

  • have Fiddler running while you work on this, and check out what is being sent n received.

HTH




回答2:


You can use YQL to get around CORS, as long as you're only doing GET requests, and not using sessions or anything tricky.

    $.getJSON("http://query.yahooapis.com/v1/public/yql?" +
        "q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent( base_url + "GetGfeQuote?strJsonRequestObject=" + JSON.stringify(LoadedGetQuoteObject())) +
        "%22&format=xml'&callback=?",
        function (theJson) {
            // ...
        }
    );


来源:https://stackoverflow.com/questions/15628016/make-ajax-call-cross-domain

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