![](/img/trans.png)
[英]when to use ajax jquery to get data from php file, Does it need to echo in php file to return data?
[英]Php does not echo the data from a jQuery Ajax submit
我擺弄jQuery.ajax()和php,我需要一些指針才能使一切正常工作:
這是PHP代碼:
if(!empty($_POST["fname"])){
$firstName = $_POST["fname"];
echo $firstName."<br />";
}
if(!empty($_POST["id"])){
$age = $_POST["id"];
echo $age;
}
這是jQuery代碼:
jQuery("#ajaxForm").submit(function(event){
event.preventDefault();
var firstName = jQuery("#firstName").val();
var age = jQuery("#age").val();
// jQuery.ajax() - Perform an asynchronous HTTP (Ajax) request.
jQuery.ajax({
type: "POST",
url: "http://localhost/profiling/index.php",
data: {fname:firstName, id:age}
}).done(function(result){
alert("Your data has been submitted!" + firstName);
});
var result;
console.log(result);
});
jQuery的值存在,我得到警告,告訴我數據已提交,firebug顯示Ajax帖子正在運行。
php為什么不獲取我的數據並回顯它?
您需要通過php獲取返回的數據並對其進行處理。 請參閱下面添加的代碼行。
jQuery("#ajaxForm").submit(function(event){
event.preventDefault();
var firstName = jQuery("#firstName").val();
var age = jQuery("#age").val();
// jQuery.ajax() - Perform an asynchronous HTTP (Ajax) request.
jQuery.ajax({
type: "POST",
url: "http://localhost/profiling/index.php",
data: {fname:firstName, id:age}
}).done(function(result){
alert("Your data has been submitted!" + firstName);
alert("This is the data returned by the php script: " + result)
});
});
您必須使用成功回調函數來處理從POST到Php頁面的響應。
您的代碼可能類似於以下內容:
/* Send the data using post and put the results in a div */
$.ajax({
url: "test.php",
type: "post",
data: values,
success: function(returnval){
alert("success");
$("#result").html('submitted successfully:' + returnval);
},
error:function(){
alert("failure");
$("#result").html('there is error while submit');
}
});
因此,您必須以某種方式將PHP的響應附加到使用jQuery的HTML元素(如DIV)
希望這對您有幫助
正確的方法:
<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode(change);
?>
然后是jquery腳本:
<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.