在尝试使用javascript手动格式化我的JSON数据并且失败后,我意识到可能有更好的方法.以下是C#中Web服务方法和相关类的代码:
[WebMethod]
public Response ValidateAddress(Request request)
{
return new test_AddressValidation().GenerateResponse(
test_AddressValidation.ResponseType.Ambiguous);
}
...
public class Request
{
public Address Address;
}
public class Address
{
public string Address1;
public string Address2;
public string City;
public string State;
public string Zip;
public AddressClassification AddressClassification;
}
public class AddressClassification
{
public int Code;
public string Description;
}
Run Code Online (Sandbox Code Playgroud)
Web服务使用SOAP/XML很有效,但我似乎无法使用javascript和jQuery获得有效的响应,因为我从服务器返回的消息与我的手工编码的JSON有问题.
我不能使用jQuery getJSON函数,因为请求需要HTTP POST,所以我使用的是低级ajax函数:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://bmccorm-xp/HBUpsAddressValidation/AddressValidation.asmx/ValidateAddress",
data: "{\"Address\":{\"Address1\":\"123 Main Street\",\"Address2\":null,\"City\":\"New York\",\"State\":\"NY\",\"Zip\":\"10000\",\"AddressClassification\":null}}",
dataType: "json",
success: function(response){
alert(response); …Run Code Online (Sandbox Code Playgroud) 我想使用ajax和jquery将表单发布到.asmx webservice,并将Webservice中的值作为JSON返回.
我正在使用ASP.NET 4.0.我知道为了从Web服务返回JSON,需要设置以下内容:(1)dataType:"json"(2)contentType:"application/json; charset = utf-8",(3)type:"POST" (4)将数据设置为某物.我测试了这个并且它工作正常(即我的webservice将数据作为JSON返回)如果所有**四都设置**.
但是,让我说在我的情况下我想做一个标准的表单帖子,即test1 = value1&test2 = value2所以contentType不是JSON但我想要回JSON {test1:value1}.这似乎不起作用,因为contentType是" application/x-www-form-urlencoded "而不是" application/json; charset = utf-8 ".
谁能告诉我为什么我不能这样做?我必须明确发送JSON以获取JSON,但如果你不使用JSON(即发布urlencoded contenttype),那么webservice将返回XML.
非常感谢任何见解:)