2011-07-08 52 views
0

我該怎麼做類似的東西:jQuery.ajax數據導致問題

$(document).ready(function() { 

    $('a').click(function() { 

     jQuery.ajax({ 
      url: 'test.php', 
         async: false, 
      success: function(data) { 
       /* here */ 
      } 
     }); 

    }); 

}) 

;

test.php的:

<?php 
header("Content-Type: application/csv"); 
header("Content-Disposition: attachment; filename=file.csv"); 
echo "field1,field2,field3"; 
?> 

我需要模擬一個下載使用jQuery的AJAX結果......這是可能的嗎?

+0

你能澄清你的意思嗎?「模擬下載」 –

回答

0

爲什麼你想用ajax做到這一點? 您可以使用直接的聯繫,例如:

 
<a href="getmyfile.php?id=1">Load .csv file</a> 

而寫所需的文件直接輸出的內容(使用正確的頭)。

或者你想在加載後做這個文件的內容嗎? 在這種情況下,嘗試:

$(document).ready(function() { 
$('a').click(function() { 
    jQuery.ajax({ 
     url: 'somefile.csv', 
        async: true, 
     success: function(data) { 
      /* here */ 
     } 
    }); 
});}) 

如果您需要從服務器獲取一些JavaScript對象使用Ajax,您可以使用JSON:

{ 
    someField: <?php echo $myfield?>, 
    someArray: [<?php echo $someNumericValue?>, '<?php someStringValue?>'] 
} 

UPD:

<html> 
    <head> 
     <title>Basic JavaScript/AJAX Example</title> 
      <script type="text/javascript" src="jquery-1.4.1.js"></script> 
      <script type="text/javascript"> 
       $(document).ready(function() {$('a').click(function() { 
        jQuery.ajax({ 
          url: 'somefile.csv', 
          async: true, 
          success: function(data) { 
           $('#myTextArea').html(data); 
           } 
          }); 
        }); 
      }); 
      </script> 
     </head> 
    <body> 
<h1>Basic JavaScript/AJAX Example</h1> 
<a href="#">Click Here to load the contents of a page into the TextArea below</a><br /> 
<textarea id="myTextArea" rows="30" cols="70"></textarea> 
</body> 
</html> 

在內容offile.csv是: test1,test2,test3

after點擊放在textarea中的'omefile.csv'的'a'內容

+0

function(data){$('#iframe')。contents()。find '主體')的html(數據)。 },也許我可以做到這一點< - 但我需要改變內容類型,我認爲 – Rpbbdoys

+0

我爲你添加小測試。這是你需要的嗎? – igoodwin