use*_*762 1 javascript ajax post
我需要编写一个脚本来接收和解析 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>
Run Code Online (Sandbox Code Playgroud)
我也尝试了很多变化,包括
data: jsondatatype:而不是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);
}
Run Code Online (Sandbox Code Playgroud)
小智 7
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);
}
});
});
Run Code Online (Sandbox Code Playgroud)
service.php
解码并处理接收到的对象
$json = filter_input(INPUT_POST, 'json');
$decoded_json = json_decode($json);
$val1 = $decoded_json->val1;
var_dump($decoded_json, $val1);
Run Code Online (Sandbox Code Playgroud)
反之亦然,如果您想从 php 发送 JSON 并将其解码为 JS
PHP
$responseArray = array();
$responseArray['key1'] = 'value1';
$responseArray['key2'] = 'value2';
echo json_encode($responseArray);
Run Code Online (Sandbox Code Playgroud)
JS
success: function (response) {
var decodedJson = JSON.parse(response);
console.log(decodedJson['key1']);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20900 次 |
| 最近记录: |