2017-04-08 85 views
-1

我試圖用這種方法
檢索使用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有。
我嘗試使用下面的代碼作爲我的參考,但是,它檢索使用將具有titleauthor到名爲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); 
     } 
     }) 
    }) 
}) 
+0

你甚至不處理響應?你怎麼能說它不工作?你甚至沒有在你的ajax調用中的回調函數 – Roljhon

+0

先生你能給我提供一些鏈接或例子嗎? – ccs

回答

0

你認爲我錯了。 .load就像是從我的理解一個ajax通話中,也請求內容,並將其發送到客戶端和顯示器。然而,ajax比這更深,因爲從ajax你可以操縱請求標題和響應。所以兩者都不是很理想。如果你想加載你的內容或從響應中顯示你的內容。不要象下面這樣:

$.ajax({ 
    dataType: "json", 
    method: "get", 
    url: "getOffers.php?useJSON" 
}).done(function(res){ 
    //do anything with the response here 
}); 
+0

是的,從某個版本開始,'.load()'也成了某種'ajax'調用。如果你想等待加載,你必須使用'.on(「load」,function(){})'功能。 – Nytrix

+0

@Nytrix了你的觀點,他試圖實際上'ajax'取代'.load'然而,他有在瞭解雙方很難,他是想實際加載內容不聽'load'事件。 – Roljhon