为什么不发送字母字符,但发送数字呢?

时间:2013-05-28 16:26:39

标签: jquery asp.net ajax

我使用AJAX(jQuery)示例here稍微修改了Deebu Jacob的ASP.NET Web方法调用版本。我已经修改了CodeBehind来取一个字符串而不是一个int,但是如果我尝试发送一个alpha字符串,当我点击按钮时,我得不到JS Alert。另一方面,如果我发送一串数字,它就可以工作,即使是空白&小数点。我添加了第二个函数,允许我在页面上发送变量而不是硬编码示例,这很好用。

我想我在AJAX调用的contentTypedataType中缺少一个概念,我还不明白。我已尝试将dataType更改为text,将contentType更改为application/x-www-form-urlencoded; charset=UTF-8,但无法使其工作。

HTML / ASP(此示例有效,如果您更改其中一个变量以包含字母字符,则不会):

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="JQueryAJAXwithIntExample.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
    function asyncServerCall(userid) {
        jQuery.ajax({
            url: 'WebForm1.aspx/GetData',
            type: "POST",
            data: "{'userid':" + userid + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                alert(data.d);
            }
        });
    }
</script>
<script type="text/javascript">
    function testMe() {
        var suffix = ".159";
        var text = "314" + suffix;
        asyncServerCall(text);
    }
</script>
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
    <input type="button" value="click me" onclick="testMe();" />
</div>
</form>
</body>
</html>

CodeBehind(在GetData方法中只改变从int到string的输入数据类型):

using System;
using System.Web.Services;

namespace JQueryAJAXwithIntExample
{
public partial class WebForm1 : System.Web.UI.Page
{
    [WebMethod()]
    public static string GetData(string userid)
    {
        /*You can do database operations here if required*/
        return "My user ID is: " + userid;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}
}

我的最终目标是将一串或一系列字符串传回服务器,以便处理成邮件和邮件。我正在研究的在线RMA项目的SQL对象。

1 个答案:

答案 0 :(得分:4)

我相信:

 data: "{'userid':" + userid + "}",

应该是这样的:

data: "{'userid':'" + userid + "'}",

请注意字符串值周围的单引号。