如何解决此未定义的索引错误? jQuery Ajax转PHP [英] How can I fix this undefined index error? Jquery Ajax to PHP
问题描述
我正在使用Jquery,Ajax和PHP尝试发送要写入mysql数据库的变量. 正在发出Ajax请求,但是php并未选择该变量.我不知道为什么会这样.
I'm using Jquery, Ajax and PHP to try and send a variable to be written in a mysql database. The Ajax request is being made but the variable is not being picked up by the php. I don't know why this is the case.
使用firebug和console.log(),我可以看到对write_results.php进行了POST
Using firebug and console.log() I can see that a POST has been made to write_results.php
如果我查看回复",则显示为
If I check the Response it says
通知:未定义索引: 2
这是我的PHP
<?php
$testscore=$_POST['testscore']; //get testscore from Ajax
include 'DB.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
if (isset($_POST['testscore'])) {
$addClient = "INSERT INTO variables (`id` ,`name`) VALUES (NULL,'$testscore')";
mysql_query($addClient) or die(mysql_error());
}
?>
这是我的Ajax脚本
<script type="text/javascript">
$(document).ready(function() {
testscore ="tryagain"; //testvalue to enter into the mysql database
$.ajax({
type: "POST",
url: "write_results.php",
data: testscore,
success: function(){
$('#box2').html("success");
}
})
});
</script>
我的问题
- 为什么$ testscore不能从ajax脚本中接收值?
- 我该如何解决?
推荐答案
您没有告诉JS如何发送POST参数.将您的JS更改为:
You're not telling the JS how to send your POST parameters. Change your JS to:
data: { 'testscore':testscore },
这等效于key=value
形式的"testscore=" + testcore
.它告诉JS和PHP您想将变量testscore
映射到键"testscore"
,然后将其用$_POST['testscore']
This is the equivalent of "testscore=" + testcore
in key=value
form. It tells JS and PHP that you want the variable testscore
to be mapped to the key "testscore"
, which you'll then pick up with $_POST['testscore']
编辑:请参见 http://api.jquery.com/jQuery .ajax/,将数据发送到服务器"
See http://api.jquery.com/jQuery.ajax/, "Sending Data to the Server"
这篇关于如何解决此未定义的索引错误? jQuery Ajax转PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!