jQuery跨站点调用ASMX服务返回值null

时间:2012-04-05 10:49:02

标签: jquery html ajax asmx cross-site

我试图通过JavaScript和jQuery从HTML页面调用asmx服务。 这是我的服务HelloWorldTest.asmx的代码:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class HelloWorldTest : System.Web.Services.WebService
{

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
    public string HelloWorld5()
    {
        string connetionString = null;
        SqlConnection connection;
        SqlDataAdapter adapter = new SqlDataAdapter();
        string sql = null;
        connetionString = System.Configuration.ConfigurationManager.ConnectionStrings["pollConString"].ToString();
        Random _rg = new Random();
        connection = new SqlConnection(connetionString);
        sql = "insert into Country (OID,country_name) values( 'Servicecalled-" + Convert.ToString(_rg.Next(0, 99999999)).PadLeft(8, '0') + "','"+System.DateTime.Now.ToString() +"')";

        connection.Open();
        adapter.InsertCommand = new SqlCommand(sql, connection);
        adapter.InsertCommand.ExecuteNonQuery();  
        return "Helloworld";
    }
}

我已在本地服务器上发布了该服务,该服务器运行在192.168.0.124和端口80中。

现在这是我的客户电话的HTML页面代码:

$.ajax({
    type: 'GET',
    url: http://192.168.0.124:80/pollservice/Services/HelloWorldTest.asmx/HelloWorld5',
    processData: true,
    data: {},               
    dataType: "json; charset=utf-8",
    responseType: "",
    success: function (data, textStatus, jqXHR) {
        processData(data, textStatus, jqXHR);
    }
});

function processData(data, textStatus, jqXHR) {                  
    alert(' data d = ' + data.d); 
}

现在问题:

当我遇到localhost时,我从服务中获得了回复。这是一个简单的字符串。但是,当我将它发布到局域网中的服务器并且我从客户端机器调用时,我得到空输出。

但是,有趣的是,日志被写入服务器。因此,通过$ .ajax(....)调用从JavaScript方法调用Helloworld5()方法。但是,对于已发布的服务器,JSON返回数据为空。

为什么会这样?我在Asp.Net集成模式下运行已发布的网站。

2 个答案:

答案 0 :(得分:0)

您将返回类型声明为JSON,但实际上返回一个裸字符串。您可能希望在返回之前构建JSON数据,例如:

// ...

string responseData = "{ d : \"";
responseData += "Hello World!";
responseData += "\" }";

return responseData;

答案 1 :(得分:0)

如果html和asmx服务在不同的服务器上运行,这可能是因为Same Origin policy。 要启用跨源ajax请求,您必须使用JSONP或CORS。

为了确保这是一个跨域问题,您可以使用chrome开发人员工具,在发生交叉原始问题的情况下,您将收到“Access-Control-Allow-Origin不允许来源”的消息。

我有类似的问题,最后我使用了JSONP。