单独测试,AJAX 会将数据发送到 API,PHP 从 JSON 文件发送 JSON 信息
我想要的是AJAX将JSON数据发送到PHP,然后将其添加到数据库中
脚本.js
$.ajax({
type: 'POST',
url: 'http://rest.learncode.academy/api/userabc/friends', //LINK OF THE PHP HERE?
data: {name: 'Person3', age: 67},
success: function(data) {
alert("Friend added!"+ data);
}
});
文件.php
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
//read the json file contents
$jsondata = file_get_contents('json.json'); // php://input?
//convert json object to php associative array
$data = json_decode($jsondata, true);
//get the employee details
$id = $data['id'];
$name = $data['name'];
$email = $data['email'];
//insert into mysql table
$sql = "INSERT INTO users(id, name, email) VALUES('$id', '$name', '$email')";
$con->query($sql);
我尝试插入url: http://localhost/WEP/JQUERYAJAX/mysl/php.php
到脚本.js并php://input
到文件.php但没有工作?有什么解决办法?
在客户端上使用它:
var data = {name: 'Person3', age: 67};
$.ajax({
url: "http://localhost/WEP/JQUERYAJAX/mysl/php.php",
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
success: function(data) {
window.alert("Friend added! "+ data);
}
});
这是在 php.php 的服务器端:
$_POST ? '' : $_POST = json_decode(trim(file_get_contents('php://input')), true);
var_dump($_POST);
警报将是:
Friend added! array(2) {
["name"]=>
string(7) "Person3"
["age"]=>
int(67)
}
这意味着你的php.php正确的json数据,你可以在php.php中以$_POST['name']和$_POST['age']的形式访问它。使用空的 php.php没有任何其他代码(只有我在此答案中发布的行代码(来测试脚本并确保避免任何其他错误。