jQuery带参数的ajax调用WebService
在调试jQuery带参数的ajax调用WebService的时候,被参数的问题搞了一下,问题是这样的:
首先在服务器端(C#, .NET2.0)定义了一个WebService, 里面有两个方法,其中一个返回:List<Person> GetPersonList(string input), 返回的是自定义的集合。
WebService代码如下:
1: using System;
2: using System.Collections.Generic;
3: using System.Collections.ObjectModel;
4: using System.Web;
5: using System.Collections;
6: using System.Web.Services;
7: using System.Web.Services.Protocols;
8:
9: [WebService(Namespace = "http://semenoff.dk/")]
10: [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
11: [System.Web.Script.Services.ScriptService()]
12: public class MySampleService : System.Web.Services.WebService
13: {
14: public MySampleService()
15: {
16: //Uncomment the following line if using designed components
17: //InitializeComponent();
18: }
19:
20: [WebMethod]
21: public string GetServerResponse(string callerName)
22: {
23: if(callerName== string.Empty)
24: throw new Exception("Web Service Exception: invalid argument");
25:
26: return string.Format("Service responded to {0} at {1}", callerName, DateTime.Now.ToString());
27: }
28:
29:
30: [WebMethod]
31: public List<Person> GetPersonList(string input)
32: {
33: List<Person> ret = new List<Person>();
34:
35: Person p = new Person();
36: p.ID = "001";
37: p.Value = "Jason Hu";
38:
39: ret.Add(p);
40:
41: p = new Person();
42: p.ID = "002";
43: p.Value = "Thomas Li";
44:
45: ret.Add(p);
46:
47: //System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
48: //return json.Serialize(ret);
49:
50: return ret;
51: }
52:
53: }
54:
55: public class Person
56: {
57: public string ID { get; set; }
58: public string Value { get; set; }
59: }
60:
客户端jQuery用ajax调用这个WebService,其中jQuery的ajax的data参数是常量可以:
1: $.ajax({
2: type: "POST",
3: contentType: "application/json",
4: url: "./WebServices/MySampleService.asmx/GetServerResponse",
5: data:"{input:56}", // ************* 常量 ******************
6: dataType: 'json',
7: success: function(result) {
8: alert("jQuery callback: " + result);
9: },
10: error: function(){
11: alert("Error occured.");
12: }
13: });
但jQuery的ajax的data参数是变量写成这样就不行:
1: $.ajax({
2: type: "POST",
3: contentType: "application/json",
4: url: "./WebServices/MySampleService.asmx/GetServerResponse",
5: data:"{input:" + user + "}", //******* 此处错,回调Error****************
6: dataType: 'json',
7: success: function(result) {
8: alert("jQuery callback: " + result);
9: },
10: error: function(){
11: alert("Error occured.");
12: }
13: });
最后继续折腾加个单引号,写成这样data:'{"callerName":"'+user+'"}' 就没问题了:
1: /// <reference src="jquery-1.3.2.js"/>
2:
3: var MyNameSpace = MyNameSpace || {};
4: MyNameSpace.Auth={};
5:
6: MyNameSpace.Auth.TestJQuery = function(user)
7: {
8: $.ajax({
9: type: "POST",
10: contentType: "application/json",
11: url: "./WebServices/MySampleService.asmx/GetServerResponse",
12: data:'{"callerName":"'+user+'"}', //注意格式!!"{callerName:abc}",可以,但 "{callerName:"+user+"}"不行,Error!
13: dataType: 'json',
14: success: function(result) {
15: alert("jQuery callback: " + result);
16: },
17: error: function(){
18: alert("Error occured.");
19: }
20: });
21:
22: $.ajax({
23: type: "POST",
24: contentType: "application/json",
25: url: "./WebServices/MySampleService.asmx/GetPersonList",
26: data: '{"input":"'+user+'"}', ////注意格式!"{input:56}",可以,但 "{input:"+user+"}"不行,Error!
27: dataType: 'json',
28: // beforeSend: function(){
29: // $("#tipsDiv").show();
30: // $("#tipsDivGT").text("Searching.... please wait");
31: // },
32: // error: function(){
33: // $("#tipsDivGT").text("Error occured!!");
34: // },
35: success: function(result) {
36:
37: //$('#dictionary').append(this.toString() + " ");
38: // alert(result.join(" | "));
39:
40: $(result).each(function() {
41: alert(this['ID'] + " " + this['Value']);
42: });
43:
44: }
45: });
46: }
47:
48: $(function() {
49: $("#btnTest").click(function() {
50: MyNameSpace.Auth.TestJQuery( $("#tbUserName").attr("value") );
51: });
52:
53: }
54:
55: );
其中参数的值如果含有双引号,就会报错,例如:
data:'{"callerName":"'+user+'"}'
如果user的值是 <a href="http://www.abc.com">Some value</a>
就会报错,解决办法是双引号转义,把 " 变成 \":user换成:user.replace(/\"/ig, "\\\"")
立此存照希望对被同样小问题困扰的同学有用!