Javascript 使用JS向Rest WS发送POST请求
我正试图用javascript向WCF服务发送REST请求。 我已经尝试了一个.net客户端的服务,效果很好 这是我在wcf服务中的示例方法:Javascript 使用JS向Rest WS发送POST请求,javascript,jquery,wcf,rest,post,Javascript,Jquery,Wcf,Rest,Post,我正试图用javascript向WCF服务发送REST请求。 我已经尝试了一个.net客户端的服务,效果很好 这是我在wcf服务中的示例方法: [OperationContract] [WebInvoke(Method="POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] bool GuardarJuan(Persona persona); 在javascript中
[OperationContract]
[WebInvoke(Method="POST",
ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
bool GuardarJuan(Persona persona);
在javascript中,我尝试了以下方法:
function sendRequest3(){
var datos='{"IdPersona":2,"Nombre":"David BQ"}';
var parameters = JSON.stringify(datos);
var req=$.ajax({
url: 'http://localhost:8732/Design_Time_Addresses/RestTEST/GuardarJuan',
type: 'POST',
data: parameters,
contentType: 'application/json',
dataType: 'jsonp'
});
}
也像这样:
function sendPost(){
var url = "http://localhost:8732/Design_Time_Addresses/RestTEST/GuardarJuan";
var persona={
IdPersona: 2,
Nombre: 'David BQ'
};
var parameters = JSON.stringify(persona);
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send(parameters);
xmlHttp.onreadystatechange= function X()
{
if(xmlHttp.readyState == 4)
{
alert(xmlHttp.responseText);
}
}
但这些都不起作用。它总是给我一个405错误方法不允许或0x80004005(NS错误失败) 谢谢 编辑: 问题解决了。。这是跨领域的问题。 我是用VS服务器做的,所以我改成了IIS,一切都很好。首先,“服务”是否与您试图与服务对话的页面位于同一个域 第二,如果您试图使用JSONP,您只能使用“GET”而不是“POST”,因为JSONP只是创建一个将响应封装在somerndmethod(response)中的函数。。。它执行您期望的代码
您可能需要使用IIS/IISExpress,并将主应用程序和wcf应用程序放在同一个主机上:端口。您排除了什么?谷歌还告诉我,可能是你以某种方式禁用了IIS服务器上的POST。我相信,如果你更改了端口号,那么你就是在更改域和跨域策略应用,这意味着你必须使用JSONP来处理此请求,或者创建一个服务器端代理来获取JSON脚本。