[英]How to send POST data in ajax?
我需要编写一个脚本来接收和解析 POST 数组中的 JSON 数组。 为了做到这一点,我首先尝试将任何旧的 JSON 数据发送到我的脚本,以便我可以使用一些东西。
我的接收脚本是用 PHP 编写的(但也可以用 Javascript 完成。)现在,我只是序列化 POST 数组并将其写入文本文件以确保有内容进入。它正在写的是一个空数组,尽管。
我正在尝试使用 ajax 请求发送数据。 这就是我现在所拥有的:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
var jsondata = JSON.stringify({
val1:"this",
val2:"that"
});
$.ajax({
url: "http://api.mydomain.com/test/index.php",
method: "POST",
data: {json: jsondata},
contentType: "application/json",
success: function(data){alert(JSON.stringify(data));},
error: function(errMsg) {
alert(JSON.stringify(errMsg));
}
});
});
</script>
</head>
<body>
</body>
</html>
我也尝试了很多变体,包括
data: jsondata
type:
而不是method:
在请求中datatype: "json"
以及其他一些我什至不记得的变体。 我错过了一些简单的东西吗? 或者有更简单的方法来完成这个吗?
编辑:添加我的 index.php 文件
if (isset($_POST)){
// This line is commented out because it breaks it.
//$jspost = json_decode($_POST['json']);
$jsser = serialize($_POST);
echo "I'm here.";
// Write to text file
$myfile = "response.txt";
$fh = fopen($myfile, 'w') or die("can't open file");
$now = date("n/j/y g:i:s a");
fwrite($fh, $now."\r\n");
fwrite($fh, "I received a POST.\r\n");
fwrite($fh, $jsser);
fwrite($fh, "\r\n\n");
fclose($fh);
}
JS
发送一个 JSON 字符串
$(document).ready(function () {
var obj = {
val1: "this",
val2: "that"
};
obj.val3 = 'these';
obj['val4'] = 'those';
$.ajax({
type: "POST",
url: "service.php",
data: {
json: JSON.stringify(obj)
},
success: function (response) {
//service.php response
console.log(response);
}
});
});
服务.php
解码并处理接收到的对象
$json = filter_input(INPUT_POST, 'json');
$decoded_json = json_decode($json);
$val1 = $decoded_json->val1;
var_dump($decoded_json, $val1);
反之亦然,如果你想从 php 发送一个 JSON 并将其解码为 JS
PHP
$responseArray = array();
$responseArray['key1'] = 'value1';
$responseArray['key2'] = 'value2';
echo json_encode($responseArray);
JS
success: function (response) {
var decodedJson = JSON.parse(response);
console.log(decodedJson['key1']);
}
这对我有用......我没有使用表单而是使用从元素收集的数据变量。 我尝试了以前的方法,但没有得到结果。
<script>
$(document).ready(function() {
var jsondata = new FormData();
jsondata.append("val1", "this");
jsondata.append("val2", "that");
$.ajax({
url: "http://api.mydomain.com/test/index.php",
method: "POST",
data: jsondata,
contentType: false,
cache: false,
processData: false,
dataType: 'json',
success: function(data){alert(JSON.stringify(data));},
error: function(errMsg) {
alert(JSON.stringify(errMsg));
}
});
});
</script>
试试这个
var jsondata = {
"val1":"this",
"val2":"that"
};
$.ajax({
url: "http://api.mydomain.com/test/index.php",
method: "POST",
data: jsondata,
contentType: "json",
success: function(data){
//your success function
},
error: function(errMsg) {
//your error function
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.