javascript 如何从 PHP 中的 jQuery.Post() 检索数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10462812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to retrieve data from jQuery.Post() in PHP?
提问by user1055650
I am currently trying to send a string to a to a php script which will eventually return a JSON file. Here is code i'm using to send the string:
我目前正在尝试将字符串发送到 php 脚本,该脚本最终将返回一个 JSON 文件。这是我用来发送字符串的代码:
var str = "testString";
$.post("php/getTimes.php", str,
function(data){
console.log(data.name);
console.log(data.time);
}, "json");
In the 'getTimes' php file I am simply trying to receive the 'str' variable I am passing. Any ideas how to do this? It seems like it should be pretty simple.
在'getTimes' php 文件中,我只是想接收我传递的'str' 变量。任何想法如何做到这一点?看起来应该很简单。
回答by VisioN
You have to name attributes in POSTdata
either with serialized string:
您必须使用序列化字符串在POST 中命名属性data
:
var data = "str=testString";
$.post("php/getTimes.php", data, function(json) {
console.log(json.name);
console.log(json.time);
}, "json");
or with map:
或地图:
var data = {
str : "testString"
};
$.post("php/getTimes.php", data, function(json) {
console.log(json.name);
console.log(json.time);
}, "json");
To handle this variable in PHP use:
要在 PHP 中处理这个变量,请使用:
$str = $_POST['str'];
回答by andyderuyter
In getTimes.php:
在 getTimes.php 中:
<?php
$var = $_POST['string']; // this fetches your post action
echo 'this is my variable: ' . $var; // this outputs the variable
?>
Also adjust:
还要调整:
$.post("php/getTimes.php", str,
to
到
$.post("php/getTimes.php", { string: str },