使用AJAX将变量javascript传递给PHP [英] Passing variable javascript to PHP using AJAX
问题描述
我正在尝试使用jQuery AJAX将单个变量从javascript传递到PHP.
I am trying to pass a single variable from javascript to PHP using jQuery AJAX.
JavaScript:
Javascript:
$(document).ready(function() {
$('.ok').on('click', function(e){
var value = 5;
$.ajax({
url: 'tabulka.php',
type: "POST",
data: {x : value},
success: function(){
alert(value);
}
});
});
});
PHP:
if($_SERVER['REQUEST_METHOD']){
$value = $_POST['x'];
echo $value;
}
我从ajax获得了具有预期值的警报,但是在PHP中,我得到了以下错误:Notice: Undefined index: value in C:\xampp\htdocs\test\tabulka.php on line 71
当我取消注释dataType: 'json'
时,我什至没有收到来自AJAX的警报.
I get the alert from ajax with the expected value but in PHP I get this error: Notice: Undefined index: value in C:\xampp\htdocs\test\tabulka.php on line 71
When I uncomment the dataType: 'json'
I don't even get the alert from AJAX.
推荐答案
您的JavaScript
Your JavaScript
data: {'value' : value}
请注意单引号和没有括号
您的PHP:
If(isset($_POST['value'])){
$val = $_POST['value'];
}
您的JavaScript格式错误. data
是一个对象,或者换句话说,是一个关联数组.
Your JavaScript was formatted incorrectly. data
is an object, or an associative array in other words.
您的PHP代码具有不必要的字符串比较.每当对PHP脚本发表文章时,您都将使用$ _POST数组访问它们.
Your PHP code has unnecessary string comparison. Whenever a post is made to a PHP script, you will access them using $_POST array.
例如,如果您是通过AJAX发布的
For instance, if you posted this via AJAX
data:{ 'name' : 'jake', 'age' : 1024}
您可以通过以下方式在PHP中访问它们
You would access them in PHP by
$name = $_POST['name']
$age = $_POST['age']
此外,明智的是使用PHP isset
在尝试访问它们之前验证post变量是否存在.这样,如果期望的发布数据不存在,您将不会有异常.
Also, it is wise to use PHP isset
to verify that a post variable exists before trying to access them. That way you will not have an exception if expected post data is not.
这篇关于使用AJAX将变量javascript传递给PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!