我在使用WCF服务时遇到一些问题:此服务应与在其他服务器上运行的AJAX客户端通信。所以,我有一个跨域问题。我搜索和工作了2天,但我找不到一些解决方案,这很容易理解。
当我使用Fiddler时,他们可以与服务器通信,但只有在将content-length属性设置为零时才能进行通信。
GET方法也有效,但PUT从不。
以下是方向的一些代码:
[DataContract]
public class Person
{
[DataMember]
private string id;
[DataMember]
private string name;
public Person(string id, string name)
{
this.id = id;
this.name = name;
}
public string Id { get; set; }
public string Name { get; set; }
}
[ServiceContract]
interface IPersonService
{
...
[OperationContract]
Person InsertPerson(Person person);
}
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
public class PersonService : IPersonService
{
[WebInvoke(UriTemplate = "/POST/PersonPost", Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public Person InsertPerson(Person per)
{
Debug.WriteLine("InsertPerson");
if (per == null)
{
return new Person("2", "null");
}
Debug.WriteLine("POST:[PersonId = {0} PersonName = {1}]", per.Id, per.Name);
return new Person("1", "InsertPerson");
}
var person = '{"per":{';
person = person + '"id":"' + '"abc123"' + '",'
person = person + '"name":"' + '"john"' + '"'
person = person + '}}';
alert(person);
$.support.cors = true;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
data: person,
processData: false,
crossDomain: true,
url: "http://localhost:59291/Person/POST/PersonPost",
success: function (data) {
alert("Post erfolgreich: ");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Fehler Post: Status " + xhr.status + " AntwortText " + xhr.responseText);
}
});
有人可以告诉我我该怎么做才能让它发挥作用: 简而言之,当我使用jQuery方法时,目前我没有与服务器的连接。
答案 0 :(得分:0)
首先,你应该使用一个对象:
var myObject ={};
myObject.Id = '';
myObject.Name ='';
并使用JSON.stringify(myObject);
可能希望从您的ajax调用中移除此内容:dataType: "jsonp",
您也可以从此问题Cross domain ajax request中查看问题。
var person = {};
person.id ="abc123";
person.name ="aaaa";
var per = {};
per.per = person;
$.support.cors = true;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(per),
dataType: "jsonp",
processData: false,
crossDomain: true,
url: "http://localhost:59291/Person/POST/PersonPost",
success: function (data) {
alert("Post erfolgreich: ");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Fehler Post: Status " + xhr.status + " AntwortText " + xhr.responseText);
}
});