jQuery对ASMX服务的跨站点调用返回值为null
我试图通过JavaScript和jQuery从HTML页面调用asmx服务。 以下是我的HelloWorldTest.asmx服务代码:jQuery对ASMX服务的跨站点调用返回值为null,jquery,html,ajax,asmx,cross-site,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
[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时,我从服务中得到一个返回。它是一个简单的字符串。但是,当我将其发布到局域网中的服务器上并从客户机调用时,我得到的是空输出
但有趣的是,日志会写入服务器。因此,Helloworld5()方法是通过$.ajax(..)调用从JavaScript方法调用的。但对于已发布的服务器,JSON返回数据为空。
为什么会这样?我正在Asp.Net集成模式下运行已发布的网站 您将返回类型声明为JSON,但实际上返回的是裸字符串。您可能希望在返回JSON数据之前构建它,例如:
// ...
string responseData = "{ d : \"";
responseData += "Hello World!";
responseData += "\" }";
return responseData;
这可能是因为html和asmx服务是否在不同的服务器上运行。 要启用跨源ajax请求,必须使用或CORS 为了确保这是一个跨源问题,您可以使用chrome developer工具,在出现跨源问题的情况下,您将收到一条消息“访问控制不允许源代码允许源代码”
我也遇到了类似的问题,最终使用了JSONP。谢谢Eliran。我有格式JSON字符串作为您的评论。但仍然没有进展。期待这个问题。。。