簡體   English   中英

jQuery和AJAX用於txt文件

[英]Jquery and AJAX for txt file

這是我的腳本

<div id="result"></div>
<script src="jquery-1.10.2.min.js"></script>
<script>
$('#year li').click(function() {
    var text = $(this).text();
    //alert('text is ' + text);
    $.post("B.php",
    {
    text: text,

      } );  
    event.preventDefault() ;
  });
</script>

單擊列表項時,它將執行php腳本。 腳本B.php創建了一些txt文件。 讓我們叫ddd.txt之一 現在,我想在單擊時將ddd.txt文件的內容加載到具有id 結果的div上。 有人可以幫我嗎?

在您的php file添加以下代碼

$file = 'ddd.txt';
$contents = file($file); 
$string = implode($contents); 
echo $string;

post success添加后,您將獲得從php文件echoed該值。假設它名為data

$('#result').text(data);

希望這可以幫助你交配.. :)

$.post("B.php",{ text: text}, function(data){
    $('#result').text(data);
}); 

或者如果jQuery> = 1.5:

$.post("B.php",{ text: text}).done(function(data){
    $('#result').text(data);
}).fail(function(){
    console.log('something went wrong', arguments);
}); 

您有兩個選擇。 您可以在生成器請求中加載結果的“同步”方法。 或“異步”方法,您在生成器運行后每x秒檢查一次結果。

同步地你可以做

$.post("B.php, { 'text': text }, function(return_data, txtStatus, jqXHR) {
    $('#result').html(return_data);
});

並讓您的php生成文件,並在結束腳本之前輸出要顯示的數據。

異步地,有幾種選擇。 最簡單的方法是使用$().load ,您可以在其中執行以下操作:

function check_results(text) {
    $('#results').load('somescript.php', { 'text' : text }, function(return_data) {
        if(return_data == "") {
            setTimeout(function(){ check_results(text); }, 1000);
        }
    });
}


$.post("B.php, { 'text': text }, function(return_data, txtStatus, jqXHR) {
    check_results(text);
});

實質上,一旦POST返回,便開始檢查文件。 如果此腳本生成大量文件並花費一些時間,但是您想獲取例如第一個文件,則可以通過在post回調函數之外調用它來與post串聯運行check results函數(這是我猜是更異步的。

顯然,該代碼是一個示例,因此,請捏一點鹽,然后對其進行修改。

我將通過$ .ajax()完成此完整操作。

$('#year li').click(function(){
    var text = $(this).text();
    $.ajax({url: 'B.php', type: 'POST', data: {'value':text}, success: function(data){
        alert(data); // alert any return values;
    }
    });
});

在B.php中,您可以使用$ _POST ['value']變量將內容發布到文件中,也可以在干凈的php代碼中添加所需的任何內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM