小弟正學習ajax中, 跟網上教學 做了以一下程序,
問題是在js 中的dataType: "html",
如我把它改成"json" 就會報錯了,
有大大可解答一下嗎? 如果想用json格式轉到 另一頁進行處理應該如何做?
謝謝
<div id='adphp'></div>
<?php
$data_array_en = [
"1" => "Apple",
"2" => "HTC",
"3" => "Samsung",
"4" => "ASUS",
"5" => "Sony"
];
$data_json_en = json_encode($data_array_en);
echo $data_json_en;
?>
<script>
var ar = <?php echo json_encode($data_array_en); ?>
$.ajax({
url: 'http_ajax.php',
type: "POST",
dataType: "html",
data: ar,
error: function() {
alert('Ajax request 發生錯誤');
},
success: function(res) {
alert('Ajax success!');
console.log(res);
document.getElementById('adphp').innerHTML = res
}
});
</script>
http_ajax.php
<?php
$data = $_POST;
foreach ($data as $value) {
echo $value."<br>";
}
?>
你的 http_ajax.php 沒有用 json 回傳給 ajax
<?php
$data = $_POST;
foreach ($data as $value) {
// echo $value."<br>";
}
echo json_encode($data);
?>