how to consume web services (own project) from html page
i have a web service project called (WS_Service) i have a html page thats trying to consume WS_Service.
i have开发者_如何学编程 web services sits on its own project (the reason i have created is because its independednt and can be called from .aspx or .html or mobile)
i dont have problem with .aspx and i have just add the reference and fire the services.
but i am not sure how i will be doing on .html page below is my code i am trying to POST to a web service:
$.ajax({
type: "POST",
url: "http://myhostname/Delete.asmx/DeleteCustomer", <<< is that right?
data: "{CustID: " + parseInt(customer_id) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
any suggustions?
First off, you can't POST to a form that's on another domain using AJAX. So make sure that you aren't trying to POST to domain1.com when the Javascript is running on domain2.com.
Assuming they are on the same domain, you are pretty close, but if you're trying to post JSON to using jQuery I would just do something like this:
var data = {
CustID: parseInt(customer_id)
};
$.post("http://myhostname/Delete.asmx/DeleteCustomer", {data: JSON.stringify(data)}, function(response) {
//success
});
That will send through your JSONified object in a POST variable called data
on the server side of things.
Don't try to mess with building the JSON yourself in a string, that will get very messy if you start sending complicated data. That's why they invented the JSON functions. $.post
is just a shortcut to $.ajax
with some default stuff already configured that should be fine for your use. If you really need to capture AJAX errors (like HTTP Status Codes), have a look at $.ajaxError
as a supplement.
You can include a simple JSON compatibility script in your page if you are supporting legacy browsers that don't have the JSON.stringify and JSON.parse functions, like https://github.com/douglascrockford/JSON-js
I suspect strongly that this line:
data: "{CustID: " + parseInt(customer_id) + "}",
should involve an object, not a string:
data: { CustID: customer_id },
or possibly:
data: { CustID: parseInt(customer_id, 10) },
精彩评论