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

发布于 2024-09-12 08:08:34 字数 1611 浏览 2 评论 0原文

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

我在 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 淹没了!

请帮忙 谢丽尔

It's me again (previous question) I am still having problems with json and xml being returned from an ajax call.

I have written a webservice in MonoDevelop version 2.2 to return my json.

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

Which returns:-

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

If I test my webservice I get:-

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

Which is exactly what I am pulling in when I make my ajax calls. My json is still wrapped in XML and therefore cannot be read.

This is my ajax call:-

$.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);
            }  
  });

If I do just json I get 500 Internal server error, if I do a POST I get 403 forbidden error.

This morning I tried doing:-

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

Only I get the exact same problems.

If I could just remove the xml from my json then I could move forward but right now I am dead in the water and I think I am drowning in ajax!

Please help
Cheryl

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

高跟鞋的旋律 2024-09-19 08:08:34

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

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

Instead of returning a string in your WebMethod, return void and use:

JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(YOUR_STRING_TO_OUTPUT));
凶凌 2024-09-19 08:08:34

一个快速但肮脏的修复方法是从 success 函数中的 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. 

 }

A quick and dirty fix is to extract your json from the xml in the success function.

$.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. 

 }
羁拥 2024-09-19 08:08:34

更改

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)
    {
    }

change

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

to

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

Complete example:

/* 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" />

signature of the web service method:

   [WebMethod(EnableSession = true)]
    public string SaveJson(string FormData)
    {
    }
意犹 2024-09-19 08:08:34

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

Make sure your service class has [ScriptService] attribute. This attribute is not added by default.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文