简体   繁体   中英

How to pass on a parameter to asp.net web service and return xml?

Currently I have a button that with jQuery/AJAX searches for all customers from a SharePoint list and my web service return an XML string. I then populate a dropdown with data from the XML.

I know wanted to pass on a parameter (customer name) for a search function and I can return what I want from the SharePoint list but my AJAX call returns error (parseerror).

To get all customers (which works):

$.ajax({
    type: "GET",
    url: "SynchroniseCustomers.asmx/GetAllCustomers",
    dataType: "text/xml",

error: function (xhr, status) {
    hideLoading();
},
beforeSend: function () {
    showLoading("customers");
},
success: function (xml) {
    hideLoading();
    populatecustomerDropdownList($(xml).text());
}

});

I am not sure on how to go on about this but I tried

var customer = CustomerName;

$.ajax({
    type: "GET",
    data: { CustomerName: JSON.stringify(customer) },
    url: "SynchroniseCustomers.asmx/GetCustomerByName",
    dataType: "json",

error: function (xhr, status) {
    hideLoading();
    alert(xhr + " " + status);
},
beforeSend: function () {
    showLoading("Customers");
},
success: function (xml) {
    hideLoading();
    populateCustomerDropdownList($(xml).text());
}
});

Can someone please point me in the right direction on how to perform this?

Thanks in advance.

Your specificing your return data type as JSON, it should be XML:

dataType: "xml"

Also this looks wrong:

populatecustomerDropdownList($(xml).text());

When you do $(xml) you access your structure just like HTML, so for example if the structure is:

<?xml version="1.0" encoding="utf-8" ?>
<RecentTutorials>
  <Tutorial author="The Reddest">
    <Title>Silverlight and the Netflix API</Title>
    <Categories>
      <Category>Tutorials</Category>
      <Category>Silverlight 2.0</Category>
      <Category>Silverlight</Category>
      <Category>C#</Category>
      <Category>XAML</Category>
    </Categories>
    <Date>1/13/2009</Date>
  </Tutorial>

jQuery:

  success: function(xml) {
     $(xml).find("Tutorial").each(function()
     {
        $("#output").append($(this).attr("author") + "<br />");
     });
  }

I don't know about returning XML data from web services but can help you with the sending bit.

If customer variable is just a simple string, use

data: { "CustomerName": customer },

If customer variable is of complex type, use

data: { "CustomerName": JSON.stringify(customer) },

For more information about passing complex types, read this article by Dave Ward .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM