【问题标题】:How to call cross domain web service of asp.net by using javascript and jquery如何使用javascript和jquery调用asp.net的跨域web服务
【发布时间】:2016-08-04 09:32:51
【问题描述】:

我正在尝试通过使用 jquery 和 asp.net Web 服务来连接跨域 Web 服务。当我尝试连接它时,我收到了error 消息,当它在同一个本地主机中时它工作正常。但是我想在它们位于不同的本地主机或不同的帖子中时获得输出,这意味着我想将我的代码托管在一台机器上,而 Web 服务在另一台机器上。 这是我的代码。

$.ajax({
           type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "http://***.***.**.***/latlangs.asmx/Get_Lat_Longs",                   
                crossDomain: true,
                async: true,                    
                data: "{ }",
                dataType: "json",                   
                success: function(data) {                       
                    alert("Success");                       
                    },
                error: function(err) {
                    alert(err.statusText);
                }
            }); 

这是我的网络服务方法或 .asmx 页面

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Web.Script.Serialization;
using System.Web.Script.Services;


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class LatLongs : System.Web.Services.WebService {

string con = @"Data Source=SERVER\QTTS;Initial Catalog=asdf;User ID=sa;Password=*****";


[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string Get_Lat_Long_Values()
{
    try
    {
        string stri = @"SELECT MAX(id) AS Expr1 FROM Temp_lat_long_values";
        SqlDataAdapter daa = new SqlDataAdapter(stri, con);
        DataTable dt = new DataTable();
        daa.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            int id = Convert.ToInt32(dt.Rows[0][0].ToString());
            stri = @"SELECT x,y,id from  Temp_lat_long_values where id='" + id + "'";
            daa = new SqlDataAdapter(stri, con);
            DataTable dt1 = new DataTable();
            daa.Fill(dt1);
            if (dt1.Rows.Count > 0)
            {
                dt1.TableName = "Values";
                DataSet ds = new DataSet();
                ds.Tables.Add(dt1);
                string daresult = DataSetToJSON(ds);
                return daresult;
            }
            else
            {
                return "No data Found";
            }
        }
        else
        {
            return "No data found";
        }
    }
    catch (Exception e)
    {
        return e.Message;
    }
}

public string DataSetToJSON(DataSet ds)
{
    Dictionary<string, object> dict = new Dictionary<string, object>();
    foreach (DataTable dt in ds.Tables)
    {
        object[] arr = new object[1];
        for (int i = 0; i <= dt.Rows.Count - 1; i++)
        {                
            arr[0] = dt.Rows[i].ItemArray;
        }
        dict.Add(dt.TableName, arr);
    }
    JavaScriptSerializer json = new JavaScriptSerializer();
    return json.Serialize(dict);
}

}

【问题讨论】:

    标签: javascript jquery asp.net web-services


    【解决方案1】:

    您的问题可以通过 JSONP 解决。来自 Exactly What IS JSONP,来自 Cameron Spear:

    JSONP 代表“带有填充的 JSON”(JSON 代表 JavaScript 对象表示法),是一种绕过 CORS(跨源资源共享)规则从另一个域获取数据的方法。

    CORS 是一组“规则”,用于在与客户端具有不同域名的站点之间传输数据。

    JSONP 使用示例:

    $.ajax({
        url: "http://***.***.**.***/latlangs.asmx/Get_Lat_Longs",
        type: "POST",
        data: "{ }",
        dataType: "jsonp",
        jsonpCallback: "localJsonpCallback"
    });
    
    function localJsonpCallback(json) {
       //You can process response from here.
    }
    

    所以您可以在您的情况下使用与上述相同的 JSONP。

    【讨论】:

    • 坦克 q Darshan jain。我更新了代码,因为你说我没有得到任何事件控制也不会进入 localJsonpCallback 方法。你能帮我解决这个问题吗
    • @KrishnaMohan,有关更多详细信息,您可以查看此链接 stackoverflow.com/questions/14221429/… 如果您仍有问题,请告诉我。
    • 我没有得到任何使用你的例子。即使它没有进入错误功能也请找到下面的代码
    • @KrishnaMohan,您是否为 cross-origin-allow 设置了标题?如果没有,请先设置,然后检查。
    猜你喜欢
    • 2012-02-11
    • 2013-05-10
    • 1970-01-01
    • 2012-09-14
    • 2013-06-23
    • 2012-02-07
    • 1970-01-01
    • 2013-08-14
    相关资源
    最近更新 更多