使ajax调用跨域

我有一个ajax调用我想成为跨域我该怎么办? 脚本如下

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

url返回以下echo json_encode($result); $result的值如果成功则可以成功,如果不成功则可以是其他任何值。

PHP以这个echo $_GET['callback']."(".json_encode($result).");";

只有在您正在进行的Web服务设置为跨域访问时,您才可以请求并获取jsonp,因此您的ajax调用必须正确且Web服务必须正确。

ajax电话

  $.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; 

现在的web服务:有一点似乎我必须在与web服务代码相同的目录中正确配置一个web配置 – .svc文件 – 这就是我所做的。

这就是我放在我的svc文件中的全部内容:

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

webconfig必须包含以下内容(注意crossDomainScriptAccessEnabled =“true”)

                      

提示

  • 在url:line附近的js代码中设置一个断点,抓住最终在url中的值:…换句话说,抓住这个如何解决

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

并将其粘贴到浏览器的地址栏中。 您可以通过这种方式获得更有意义的错误消息

  • 当你处理这个问题时让Fiddler运行,并检查收到的是什么。

HTH

你可以使用YQL绕过CORS,只要你只做GET请求,而不是使用会话或任何棘手的东西。

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