使用 jQuery 创建表单形式的查询字符串不起作用

Create a querystring out of form with jQuery isn't working

本文关键字:查询 字符串 不起作用 jQuery 创建 表单 使用      更新时间:2023-09-26

我想发送一个ajax请求,但我尝试构建的查询字符串为空。

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>This is a project to show how to use RESTful</title>
</head>
<body>
<script type="text/javascript">var contexPath = "<%=request.getContextPath()%>";</script>
<script src="<%=request.getContextPath()%>/js/jquery.js"></script>

<script type="text/javascript">
function doAjaxPost() {
    var queryString = $('#htmlform') // empty
    alert("doAjaxPost Called:" + queryString + ":");
    $.ajax({
        ...
        ...
    });
}​    </script>
<H1>Add Employee</H1>
<p>
<form name="htmlform">
<table border=1>
    <thead><tr>
        <th>ID</th>
        <th>Name</th>
        <th>Email</th>
    </tr></thead>
    <tr>
        <td><input  type="text" name="ID" maxlength="5" size="3"></td>
        <td><input  type="text" name="Name" maxlength="10" size="10"></td>
        <td><input  type="text" name="Email" maxlength="10" size="10"></td>
    </tr>
</table>
<input type="button" value="Save Employee" onclick="doAjaxPost();" />
<p>
<p>
</form>
[<a href="http://localhost:8080/RESTful/service/employees">List all Employees</a> | <a href="add.jsp">Employee Form Test</a>]
</body>
</html>

更改自:

<form name="htmlform">

自:

<form id="htmlform">

和来自:

var queryString = $('#htmlform')

自:

var queryString = $('#htmlform').serialize();

你正在使用jQuery选择一个HTML对象,但你没有从中得到任何东西(当你将它附加到url字符串时,queryString仍然是一个jQuery对象)。

尝试以下操作

var queryString = $('#htmlform').serialize();

这应该会导致表单被序列化为字符串,此时追加它应该可以正常工作。

您需要

在表单上说id="htmlform"才能使$("#htmlform")正常工作。