所以我有这个 jquery 代码:
$(function(){
var url = 'template/traitComTest.php';
window.onload = function(e) {
// $(".formCom").ajaxForm({url: 'template/traitComTest.php', type: 'post'});
$.ajax({
type: "POST",
url: url,
data: $( ".formCom").serializeArray(),
success: function(reponse){
console.log(reponse);
}
});
}
});
使用这个 php 代码:
if (isset($_REQUEST)) {
$adresse = $_POST['adresse'];
$com = $_POST['commentaire'];
$sql = $bdd->prepare('UPDATE tempSelector_template SET commentaire= :com WHERE exemple = :exem ');
$sql->execute(array(
":com" => $com,
":exem" => $adresse
));
$myData1 = array('result' => $sql);
echo json_encode($myData1);
$sql->closeCursor();
$sqlSelect = $bdd->prepare("SELECT commentaire FROM tempSelector_template WHERE exemple= :exemp");
$sqlSelect->execute(array(
":exemp" => $adresse
));
$myData = array('result1' => $sqlSelect);
echo json_encode($myData);
}
我从 chrome 控制台上的 ajax 收到此响应 =>
{"result":{"queryString":"UPDATE tempSelector_template SET commentaire= :com WHERE exemple = :exem "}}{"result1":{"queryString":"SELECT commentaire FROM tempSelector_template WHERE exemple= :exemp"}}
我的问题是我无法访问 json 中的数据,需要您的帮助
最佳答案
好吧,你基本上返回了 2 组独立的 json 编码。但事实并非如此。通过ajax读取时只能接受一组json。不是两个。在您的 php 脚本中,我看到您已包含以下部分。
$myData1 = array('result' => $sql);
echo json_encode($myData1);
和
$myData = array('result1' => $sqlSelect);
echo json_encode($myData);
您应该删除这两个部分并使用 array_merge 将它们合并为一个数组
$myData1 = array('result' => $sql);
$myData = array('result1' => $sqlSelect);
echo json_encode(array_merge(myData1, $myData));
还在您的 ajax 请求中,将 dataType 设置为 json
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $(".formCom").serializeArray(),
success: function(reponse){
console.log(reponse);
});
关于javascript - 带有JSON返回的Jquery ajax无法访问JSON内部的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48114931/