我已经在网上搜索了一段时间并尝试了很多修复方法,但我仍然无法让我的代码正常运行。当用户单击带有 SubCategory
类的链接时,我想通过 JavaScript 中的 AJAX 调用将该超链接传递到 php 。 click
事件被正确检测到,并且 ajax 调用返回成功 alert
,但是当我尝试访问 php 中的变量时,它说 $ _POST
数组为空。
我不明白为什么我无法访问 php 中的 $_POST['send_link']
变量。
这是我的index.html的一部分:
<table border="1" width=50%>
<tr>
<td><b>For Sale</b></td>
<td><b>Services</b></td>
<td><b>Jobs</b></td>
<td><b>Country</b></td>
<td><b>Locations</b></td>
</tr>
<tr>
<td><a class = "SubCategory" href="FormData.php">Books</a></td>
<td>Computer</td>
<td>Full-Time</td>
<td>USA</td>
<td>Cupertino</td>
</tr>
<tr>
<td><a class = "SubCategory" href="FormData.php">Electronics</a></td>
<td>Financial</td>
<td>Part-Time</td>
<td>India</td>
<td>Mumbai</td>
</tr>
<tr>
<td><a class = "SubCategory" href="FormData.php">Household</a></td>
<td>Lessons</td>
<td>Volunteering</td>
<td>Sweden</td>
<td>Stockholm</td>
</tr>
</table>
这是我的核心。js
$( document ).ready(function() {
$(".SubCategory").click(function(){
var link = $(".SubCategory").text();
$.ajax({
type: 'POST',
url: 'FormData.php',
data: { send_link: link },
async: false,
success: function(data) {
alert("success ");
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert("fail");
}
});
});
});
这是我的FormData.php
<?php
// Connects to your Database
var_dump($_POST);
if (isset($_POST['send_link'])) {
var_dump($_POST['send_link']);
}
?>
来自 Chrome 的请求:
Request URL:
http://localhost/pkanekal/FormData.php
Request Method:GET
Status Code:200 OK
200 OK
Request Headersview source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:
en-US,en;q=0.8
Connection:keep-alive
Cookie:
PHPSESSID=mj74gqocdse6a59kun1b36ndl5
Host:localhost
Referer:
http://localhost/pkanekal/index.html
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36
Response Headersview source
Connection:Keep-Alive
Content-Length:
1303
Content-Type:text/html
Date:
Wed, 14 Aug 2013 20:31:36 GMT
Keep-Alive:timeout=5, max=99
Server:
Apache/2.4.4 (Unix) PHP/5.5.1 OpenSSL/1.0.1e mod_perl/2.0.8-dev Perl/v5.16.3
X-Powered-By:PHP/5.5.1
最佳答案
需要更改您的选择器,因为现在您正在尝试选择每个 .SubCategory
中的文本
var link = $(this).text();
您还需要阻止 anchor 单击的默认操作。 (也可以将 href 更改为 #
,因为您是在脚本中直接引用它。
$(".SubCategory").click(function(event){
event.preventDefault();
// your code
});
关于php - AJAX 未将数据传递给 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18240209/