我試圖用這種方法
檢索使用jQuery的AJAX從PHP
$(document).ready(function() {
'use strict';
$('#JSONoffers').load('getOffers.php?useJSON')});
但檢索使用SQL代碼在PHP
我成功地檢索數據從數據庫中的數據的數據,我要求使用檢索數據$.ajax()
方法。
所以問題來了。 這是我的PHP的部分代碼。
if (isset($_REQUEST['useJSON'])) {
// echo what getJSONOFfer returns
echo getJSONOffer($conn);
}
function getJSONOffer($conn) {
$sql = "select eventTitle, catDesc, eventPrice from te_events_special_offers inner join te_category on te_events_special_offers.catID = te_category.catID order by rand() limit 1";
$rsOffer = mysqli_query($conn, $sql);
//$offer = mysqli_fetch_all($rsOffer, MYSQLI_ASSOC);
$offer = mysqli_fetch_assoc($rsOffer);
return json_encode($offer);
}
首先,我想告訴大多數例子中或從類似這樣的問題,但至少,他們有JSON文件或其他價值的互聯網上找到問的問題,我不以我的PHP有。
我嘗試使用下面的代碼作爲我的參考,但是,它檢索使用將具有title
,author
到名爲JSON文件。
$(document).ready(function() {
'use strict';
$('#getBooks').click(function() {
$.ajax({
dataType: "json",
method: "get",
url: "server/books.json"}
)
.done(function (data, status, jqxhr) {
var bookList = $('#bookList').append('<dl/>');
window.console && console.log(status + '\n'+data.books);
$(data.books).each(function() {
$(bookList).find('dl').append("<dt><h3>"+this.title+
"</h3></dt><dd><p>"+this.author+
"</p><p>"+this.description+"</p></dd>");
});
}
)
.fail(function(jqxhr, textStatus, errorThrown) {
window.console && console.log(textStatus + ': ' + errorThrown);
}
);
$(this).attr("disabled", true);
});
});
其實,在我的php中只有sql代碼。
另外,我嘗試以下方法,但它不工作,也沒有在控制檯上的任何錯誤(這是相當難受,查找錯誤/錯誤)。
$(document).ready(function() {
'use strict';
//change the onclick to .load
$('#JSONoffers').load(function() {
$.ajax({
dataType: "json",
method: "get",
url: "getOffers.php?useJSON"}
)}
});
})
有人請幫我this.Much欣賞!
而現在,我參考其他來源嘗試下面的代碼,仍然不能正常工作。
$(document).ready(function() {
'use strict';
//$('#JSONoffers').load('getOffers.php?useJSON')
$('#JSONoffers').load(function() {
$.ajax({
dataType: "json",
url: "getOffers.php?useJSON",
success : function(data){
$('#JSONoffers').html(data);
}
})
})
})
你甚至不處理響應?你怎麼能說它不工作?你甚至沒有在你的ajax調用中的回調函數 – Roljhon
先生你能給我提供一些鏈接或例子嗎? – ccs