[英]jQuery and AJAX, 'post' data to .PHP
在使用jQuery-AJAX-thing(更改名為div1的div的內容)的html文檔中,我似乎無法獲取123.php返回信息。 我對JavaScript,PHP和html相當陌生; 但現在嘗試了一些教程,但似乎無法滿足我的需求,因此確實會有所幫助。
這是我的123.html,應該使用AJAX-jQuery來調用我的123.php
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
type: "POST",
url: "/123.php",
data:{id:"3", name:"John Doe"},
success:function(response){
alert('ok-'+data+'-'+respText+'-'+xhr);
$("#div1").html(respText);
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
</script>
</head>
<body>
連同123.php
<?php
$my_id = trim($_REQUEST['id']);
$my_name = trim($_REQUEST['name']);
$file = '123.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append to the file
$current .= 'time:' . time() . ',id:' . $my_id . ',name:' . $my_name . "\n";
// Write the contents back to the file
file_put_contents($file, $current);
echo 'received following: id: ' . $my_id . ' and name: ' . $my_name;
?>
123.txt只是為了查看php文件是否響應,並且確實可以,但是只有當我使用'post'方法通過/123.php?id=7&name=Jane%20Doe Elewhere時,才沒有響應(從JavaScript的)
所以我想這就是AJAX / jQuery的結構; 對於上面列出的嘗試,我在JavaScript控制台中收到錯誤“未捕獲的錯誤:未定義引用”
當我改用以下123.html時(替換其他123.html)
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").post("/123.php",{id:"3",name:"John Doe"},function(data,status){alert("Data: " + data + "\nStatus: " + status);});
});
});
</script>
</head>
<body>
<div id="div1">Text that should be changed</div>
<button>Press me, I'm a button</button>
</body>
</html>
我收到“未捕獲的TypeError:未定義不是函數”,我試圖查找它,有人寫道,可以解決插入問題
(function ($) {
$(document);
}(jQuery));
但是,它卻沒有(將其插入到script-start-tag的正下方)
我似乎無法弄清楚自己在做錯什么,因此我真的向尋求幫助和方向提供了建議。
提前致謝
您的php不返回JSON或XML,因此您無法獲取數據。 取代這個
success:function(response){
alert('ok-'+data+'-'+respText+'-'+xhr);
$("#div1").html(respText);
},
有了這個
success:function(response){
alert('ok-'+response);
$("#div1").html(response);
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.