2

我的 Jqueryajax 调用有问题,它将通过跨域使用我的一种 Web 服务方法。我一直在尝试所有可能的方法来完成,但仍然没有成功。请帮我解决我做错的事情。我可能需要为某些安全设置配置 Web 服务器吗?下面是我的代码。如果您对我的代码有任何疑问,请告诉我。

//Using Ajax Post
//Webservice will return JSON Format
//Doesn't work in both FF and IE when host to live server , work in local
//Error : Access is denined in xxxx.js in IE
//Http 403 Forbidden in FF , FF request header is OPTION
//this approach is the simplest and best way for me to use


    var myID = $("myID").val();
   $.ajax({
    type: "POST",        
    url: "http://www.mywebsite.com/webservice/Webservice.asmx/getInfo",
    data: "{myID:'"+ myID + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data) {

           Dostuff(data);
        },

    error: FailureCallBack

});

我的网络服务看起来像这样

using System.Web.Script.Services;
[WebService(Namespace = "http://www.mywebsite.com/webservice/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class Webservice : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public object getInfo(string myID)
    {       
            //Do stuff here
            return getJSONDataFromDataSet(_DS); 
    } 


}

 

//second Approch <br/>
//Using Ajax GET , webservice will return XML Format <br/>
//Doesn't work in both FF and IE when host to live <br/>
//Error : Access is denined in xxxx.js in IE <br/>
//returning XML data in FF but showing nothing in page <br/>

var myID = $("myID").val();
     $.ajax({

        type: "GET",

        url: "http://www.mywebsite.com/webservice/Webservice.asmx/getInfo?myID="myID"&callback=?",    

        success: function(data) {

                Dostuff(data);
            },

        error: FailureCallBack

    });

网络服务

public SerializableDictionary<string, object> getInfo(string myID)
    {         
     //Do stuff here
            SerializableDictionary<string, object> obj = getJSONFromDataTable(_DS);            
            return obj;            
    }

 

//third Approch
//Using normal GET , webservice will return XML Format
//same problem with second approch



var myID = $("myID").val();
    var xmlhttprequest = createRequestObject();
    var url = 'http://www.mywebsite.com/webservice/Webservice.asmx/getInfo?myID='myID'';
    xmlhttprequest.open("GET", url, true);
    xmlhttprequest.onreadystatechange = getData;
    xmlhttprequest.send(null);
function getData() 
{
  if ((xmlhttprequest.readyState == 4) &&( xmlhttprequest.status == 200))
  {    
    var myXml = xmlhttprequest.responseXML;
    Dostuff(myXml);
  } 
}
function createRequestObject() 
{
      if (window.XMLHttpRequest) 
      {
                return xmlhttprequest = new XMLHttpRequest(); 
      } 
      else if (window.ActiveXObject) 
      {  
            return xmlhttprequest = new ActiveXObject("Microsoft.XMLHTTP"); 
      } 
}

Web服务与第二种方法相同

编辑:现在我得到访问被拒绝,IE 中 POST 和 GET 请求的 javascript 错误。在提琴手我可以看到 Firefox 返回 Xml 数据但页面中没有显示,所以我在 getData 函数中放置了一个警报框,myXml 变量值始终为空,奇怪的是我只放置了 1 个警报框,它显示警报 3 次。下面是我的代码

  var myID = $("myID").val();
    var xmlhttprequest = createRequestObject();
    var encodeUrl = escape(_utf8_encode("http://www.mywebsite.com/webservice/Webservice.asmx/getInfo?myID="myID)); 
    var url = 'http://www.mywebsite.com/webservice/proxy.aspx?url='+encodeUrl;
    xmlhttprequest.open("GET", url, true); //**ACCESS IS DENIED HERE in this line!!!!**
    xmlhttprequest.onreadystatechange = getData;
    xmlhttprequest.send(null);


function getData() 
{
    var myXml = xmlhttprequest.responseXML;
    alert(myXml); //ALWAYS NULL and show alert 3 times????
    DoStuff(myXml);
}

请帮忙。此致

4

3 回答 3

3

出于安全原因,ajax 请求将无法跨域工作。有两种解决方案。

  1. 向同一服务器发出请求,然后使用基于服务器的代理机制向另一个域发出请求。

  2. 使用“JSONP”,这是一种生成类似 ajax 的请求的替代交叉方式。jQuery 通过 dataType: jsonp 而不是 json 支持这一点,并且通过他们的 api 文档有进一步的解释。此博客条目可能有用 - http://bloggingabout.net/blogs/adelkhalil/archive/2009/08/14/cross-domain-jsonp-with-jquery-call-step-by-step-guide.aspx

于 2011-01-29T03:45:08.007 回答
1

您需要在您的域上创建代理并通过请求,在这里解释:http: //www.johnchapman.name/aspnet-proxy-page-cross-domain-requests-from-ajax-and-javascript/

于 2011-01-29T03:37:51.440 回答
0

非常感谢所有的回复和帮助。我已经解决了这个问题:D 解决方案是使用 JSONP 和 Javascript 动态注入到 html 页面。下面是代码

HTML

<body>
<script type="text/javascript">
var url = "http://www.mywebsite.com/Javascript/MYJS.js";

var script = document.createElement("script");       
script.setAttribute("src",url);
script.setAttribute("type","text/javascript");                
document.body.appendChild(script);
</body>
</script>

MYJS.js

var myID = $("#myID").val();
var url = "http://www.mywebsite.com/Webservice.aspx/getInfo?myID="+myID+"";

   if (url.indexOf("?") > -1)
            url += "&jsonp=" ;
        else
            url += "?jsonp=" ;
        url += "ShowInfoCallback" + "&" ; //Important put ur callback function to capture the JSONP data

       url += new Date().getTime().toString(); // prevent caching        




var script = document.createElement("script");        
    script.setAttribute("src",url);

    script.setAttribute("type","text/javascript");                
    document.body.appendChild(script);


function ShowInfoCallback(data)
{
 DoWhateverYouWant(data);    
}

Webservice.aspx.cs

using System.Web.Script.Serialization;
public partial class Webservice : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.QueryString["myID"]))
            this.getInfo();
        else
            this.getInfoDetails();

    }
    public void getInfo()
    {
        string Callback = Request.QueryString["jsonp"];
        string encryptedID = Request.QueryString["myID"];

        //Dowhateveryouwanthere

        object obj = getJSONFromDataTable(myDataSet.Tables[1]);
        JavaScriptSerializer oSerializer = new JavaScriptSerializer();
        string sJSON = oSerializer.Serialize(obj);
        Response.Write(Callback + "( " + sJSON + " );");
        Response.End();
    }
    public void getInfoDetails()
    {
        //Same as above
 //returning 2 tables , Info and InfoDetails
        Response.Write(Callback + "( { 'Info' : " + sJSONDetails +",'InfoDetails' : "+ sJSONService + " } );");
        Response.End();
    }
}

再次感谢

于 2011-02-01T01:16:06.143 回答