对我的Web服务的Ajax查询是在我的json中返回xml - 第2部分

时间:2010-07-29 14:15:31

标签: javascript ajax json jsonp

又是我(previous question)我仍然遇到json和xml从ajax调用返回的问题。

我在MonoDevelop 2.2版中编写了一个Web服务来返回我的json。

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string  getLocationJ(){}

返回: -

JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(bigPM);
return json;

如果我测试我的网络服务,我得到: -

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">[{"placeName":"XXXX","address":"Some    Address","lat":12121,"lng":12121}]</string>

当我进行ajax调用时,这正是我所说的。我的json仍然用XML包装,因此无法读取。

这是我的ajax电话: -

$.ajax({
  type: "GET",
  url: theURL,
  async: true,
  data: {minLong:minLon, maxLong:maxLon, minLat:minLat, maxLat:maxLat},
  cache: false,
  dataType: "jsonp",
  contentType: "application/xml; charset=utf-8",
  success: function (data) {
    alert('in here');



  },
  error:function (xhr, ajaxOptions, thrownError){
                alert(xhr.status);
                alert(thrownError);
                alert(xhr.statusText);
            }  
  });

如果我只是json我得到500内部服务器错误,如果我做了POST我得到403禁止错误。

今天早上我尝试过: -

$.getJSON(theURL, {minLong:minLon, maxLong:maxLon, minLat:minLat, maxLat:maxLat}, function(data) {
 );
});

只有我得到完全相同的问题。

如果我可以从我的json中移除xml然后我可以向前移动但是现在我已经死在水中我觉得我淹没在ajax中!

请帮忙 谢丽尔

4 个答案:

答案 0 :(得分:1)

不是在WebMethod中返回字符串,而是返回void并使用:

JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(YOUR_STRING_TO_OUTPUT));

答案 1 :(得分:0)

更改

contentType: "application/xml; charset=utf-8",

contentType: "application/json; charset=utf-8", 

完整示例:

/* in this case I am using */
       <script src="Js/json2.js" type="text/javascript"></script>

  // available at: http://www.json.org/js.html

function jsonObject()
{
};
var phoneListObject = new jsonObject();

function SaveJsonObject()
{
    phoneListObject.Control = new jsonObject();
    phoneListObject.Control.CustomerId = $("#CustomerId").val();
    phoneListObject.Control.CustomerName = $("#CustomerName").val();
    phoneListObject.ListBody.PhonesBlock = new jsonObject();
    phoneListObject.ListBody.PhonesBlock.Phone = new Array();
    $('#PhonesBlock .Phone').each(function(myindex)
    {
        phoneListObject.ListBody.PhonesBlock.Phone[myindex].PhoneNumber = $(".PhoneNumber input", this).val();
        phoneListObject.ListBody.PhonesBlock.Phone[myindex].PhoneName = $(".PhoneName input", this).val();
     });
 };

 $(function()
{
    function SaveCurrentList()
    {
        SaveJsonObject();
        var currentSet = phoneListObject;
        var formData = { FormData: currentSet };
        phoneListJSON = JSON.stringify(formData);
        var FormData = "{ FormData:" + JSON.stringify(phoneListJSON) + "}";
        SavePhoneListData(FormData);
    };
    function SavePhoneListData(phonesData)
    {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data: phonesData,
            dataFilter: function(data)
            {
                var msg;
                if ((typeof (JSON) !== 'undefined') &&
        (typeof (JSON.parse) === 'function'))
                    msg = JSON.parse(data);
                else
                    msg = eval('(' + data + ')');
                if (msg.hasOwnProperty('d'))
                    return msg.d;
                else
                    return msg;
            },
            url: "../../WebServices/ManagePhones.asmx/SaveJson",
            success: function(msg)
            {
                SaveSuccess(msg);/* the JSON is in the msg, create this function to do what you want with it. */
            },
            complete: function(xhr, textresponse)
            {
                var err = eval("(" + xhr.responseText + ")");
            },
            error: function(msg)
            {
            },
            failure: function(msg)
            {
            }
        });
    };
    $('#btnSave').click(function()
    {
        SaveCurrentList();
    });
});

/* json data snip */
{"FormData":{"Control":{"CustomerId":"12345y6","CustomerName":"Joe Customer"},"PhonesBlock":{"Phone":[{"PhoneNumber":"234-233-2322","PhoneName":"son harry"},{"PhoneNumber":"234-233-2323","PhoneName":"son frank"},{"PhoneNumber":"234-233-2320","PhoneName":"momk"}]}}}

/*XML of the form data:*/
<FormData>
    <Control>
        <CustomerId>12345y6</CustomerId>
        <CustomerName>Joe Customer</CustomerName>
    </Control>
    <PhonesBlock>
        <Phone>
            <PhoneNumber>234-233-2322</PhoneNumber>
            <PhoneName>son harry</PhoneName>
        </Phone>
        <Phone>
            <PhoneNumber>234-233-2323</PhoneNumber>
            <PhoneName>son frank</PhoneName>
        </Phone>
        <Phone>
            <PhoneNumber>234-233-2321</PhoneNumber>
            <PhoneName>momk</PhoneName>
        </Phone>
    </PhonesBlock>
</FormData>

/* form layout snip */

<div class="control">
    <div class="customer">
        <input typeof="text" id="CutomerId" />
        <input typeof="text" id="CutomerName" />
    </div>
    <div class="phoneslist" id="PhonesBlock">
        <div class="Phone">
            <input typeof="text" class="PhoneNumber" />
            <input typeof="text" class="PhoneName" />
        </div>
        <div class="Phone">
            <input typeof="text" class="PhoneNumber" />
            <input typeof="text" class="PhoneName" />
        </div>
        <div class="Phone">
            <input typeof="text" class="PhoneNumber" />
            <input typeof="text" class="PhoneName" />
        </div>
    </div>
</div>
<input id="buttonSave" class="myButton" type="button" value="Save" />

Web服务方法的签名:

   [WebMethod(EnableSession = true)]
    public string SaveJson(string FormData)
    {
    }

答案 2 :(得分:0)

快速而又脏的修复是从成功函数中的xml中提取json。

$.ajax({
  type: "GET",
  url: theURL,
  async: true,
  data: {minLong:minLon, maxLong:maxLon, minLat:minLat, maxLat:maxLat},
  cache: false,
  dataType: "jsonp",
  contentType: "application/xml; charset=utf-8",
  success: function (data) {

data = extractJsonFromXml(data); 
  //you have to write extractJsonFromXml function in js, you could use substring, or a regex replace. 

 }

答案 3 :(得分:0)

确保您的服务类具有[ScriptService]属性。默认情况下不会添加此属性。