我的問題是,我需要包括一個DIV裏面的PHP文件按鈕時無需重新加載頁面按下。包括使用jQuery和AJAX一個DIV內PHP文件
有一個在「的jsfiddle」文件甚至更多的解釋。
下面是一個包含文件的jsfiddle。
感謝您的時間。我很樂意根據要求提供任何信息。
我的問題是,我需要包括一個DIV裏面的PHP文件按鈕時無需重新加載頁面按下。包括使用jQuery和AJAX一個DIV內PHP文件
有一個在「的jsfiddle」文件甚至更多的解釋。
下面是一個包含文件的jsfiddle。
感謝您的時間。我很樂意根據要求提供任何信息。
嘗試以下操作:
<button name="Change" id="Change">Change Div</button>
你是一個ID指定點擊功能,但沒有ID設置按鈕。
見here for your updated jsfiddle
您已經打上Change
名稱更改按鈕,但試圖與change
的ID來選擇它。另外,你還沒有告訴jsfiddle包含jQuery。
你可以用load()函數嘗試jQuery的
你不能在與AJAX PHP文件,而是在AJAX服務器端腳本,這是PHP的響應(其中有同樣的效果)。
載入中...的JS文件(代碼):
function ajaxalizeDiv()
{
$.ajax({
type: "get",
url: "/path/to/the/php/you/want/to/include",
data: {
// Anything in json format you may want to include
id: myvarwithid, // descriptive example
action: "read" // descriptive example
},
dataType: "json",
success: onAjax
});
}
function onAjax(res)
{
if(!res || !res.text)
return;
$("#mydiv").html(res.text);
}
這裏而來的PHP文件:
<?php
$id = (int) @$_GET['id']; // same as in data part of ajax query request
$action = @$_GET['action']; // same as in data part of ajax query request
$text = '<a href="/index.php?id=' . $id . '&action=' . $action . '">click me</a>';
// Note this is short example you may want to echo instead of die
// You may use not JSON, but raw text. However, JSON is more human-friendy (readable)
// and easy to maintain.
// Note also the array keys are used in the onAjax function form res (response).
die(json_encode(array('text' => $text /* and anything else you want */)));
?>
PHP是一種服務器端腳本語言,它將在JavaScript腳本執行之前執行。
因此,您不能使用執行PHP代碼,但是,您可以嘗試.ajax()
向可以實現PHP代碼的服務器創建AJAX請求。
請參閱http://api.jquery.com/jQuery.ajax/如果你有使用.ajax()
麻煩。
注意:在.ajax()
方法中,存在一個名爲beforeSend
的設置,該設置「可用於在發送之前修改jqXHR(在jQuery 1.4.x,XMLHTTPRequest中)」對象。希望這種方法以任何方式幫助你。
然後,你的JavaScript代碼將是這樣的:
$(document).ready(function(){
$("#Change").click(function(){
//doing AJAX request
$.ajax({
url:"include/start10.php",
beforeSend:function(){
$('#myDiv').fadeOut('slow');
},
success:function(data){
// do something with the return data if you have
// the return data could be a plain-text, or HTML, or JSON, or JSONP, depends on your needs, if you do ha
$('#myDiv').fadeIn('slow');
}
});
});
});
這將工作與PHP頁面上完整?我希望這個功能像「PHP include」一樣工作。 – tushar747 2012-01-06 13:53:41
@ tushar747很抱歉如此遲到的迴應。與PHP相比,Javascript是一種完全不同的語言,但它們可以在HTML文檔中一起工作,例如:'
<?php echo'這裏是PHP代碼'; ?>' – 2017-03-24 10:57:57
對不起,那是對的jsfiddle錯誤的,不符合我的實際代碼。對於那個很抱歉。 – tushar747 2012-01-06 13:54:46