Home > php教程 > PHP开发 > Simple example of JQuery Ajax WebService passing parameters

Simple example of JQuery Ajax WebService passing parameters

高洛峰
Release: 2016-12-08 10:47:56
Original
1373 people have browsed it

When using jQuery to implement Ajax in Asp.NET, aspx, ashx, and WebService can be used on the server side. I recently studied the WebService method. This post gives a very detailed example of jQuery Ajax method call jQuery Ajax method call Asp.Net WebService detailed example code, but does not give a detailed explanation. There were several details that I didn't pay attention to at first, but it took a lot of effort to solve them:

1) The key field name in the client data must be strictly consistent with the server-side method parameters.

For example, the client:

//有参数调用
   $(document).ready(function () {
     $("#btn2").click(function () {
       $.ajax({
         type: "POST",
         contentType: "application/json",
         url: "WebService.asmx/GetWish",
         data: "{value1:'心想事成',value2:'万事如意',value3:'牛牛牛',value4:2009}",
         dataType: 'json',
         success: function (result) {
           $('#dictionary').append(result.d);
         }
       });
     });
   });
Copy after login

The GetWish function parameters on the server side must be written as value1, value2, value3, value4:

[WebMethod]
public string GetWish(string value1, string value2, string value3, int value4)
{
  return string.Format("祝您在{3}年里 {0}、{1}、{2}", value1, value2, value3, value4);
}
Copy after login

2) The method for the client to pass objects to the server:

Client Code:

//传入对象
   $(function () {
     $("#btn6").click(function () {
       obj = new Object();
       obj.ID = "1";
       obj.Value = "aaa";
       //'{"obj":{"ID":"1",Value:"Horse"}}'
       var d = '{"obj":' + JSON.stringify(obj) + '}';
       $.ajax({
         type: "POST",  //访问WebService使用Post方式请求
         contentType: "application/json", //WebService 会返回Json类型
         url: "WebService.asmx/ParmsObject", //调用WebService的地址和方法名称组合 ---- WsURL/方法名
         data: d,     //这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到   
         dataType: 'json',
         success: function (result) {
           alert(result.d);
         },
         error: function (result) {
           alert("fail");
         }
       });
     });
 
   });
Copy after login

Server-side code:

[WebMethod]
public string ParmsObject(Class1 obj)
{
 
  return obj.ID + ":" + obj.Value;
}
Copy after login

Debugging environment: VS2010+jquery-1.3.2.min.js


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template