2016-06-11 103 views
0

我試着通過ajax調用來獲得excel表單的php當我加載特定的php的url給我的輸出,但是當相同的php通過ajax與一些ajax值調用時什麼也沒有顯示..沒有知道該怎麼做ajax獲取Excel表格php

AJAX:

var fromdate= $("#fromdate").val(); 
var ToDate= $("#ToDate").val(); 
var Year= $('#Year').val(); 
var Category=$('#Category_1').val(); 

          $.ajax({ 
           url: "http://localhost/demo.php", 
           type: "post", 
           data: { 
            fromdate:fromdate,ToDate:ToDate,Year:Year,Category:Category 
           }, 
           success: function(responsecon) { 
             window.open('http://YOUR_URL','_blank'); 


           } 

          }); 

PHP:

<?php 
    $conn=mysqli_connect('localhost','root','0000','xxxxx'); 

    $filename = "users_export"; 
    $fromdate = mysqli_real_escape_string($mysqli,trim($_POST["fromdate"])); 
    $ToDate = mysqli_real_escape_string($mysqli,trim($_POST["ToDate"])); 
    $Year = mysqli_real_escape_string($mysqli,trim($_POST["Year"])); 
    $Category = mysqli_real_escape_string($mysqli,trim($_POST["Category"])); 
    $sql = "Select * from xxxxxxxxxxx where category='$Category'"; 
    $result = mysqli_query($conn,$sql) or die("Couldn't execute query:<br>" . mysqli_error(). "<br>" . mysqli_errno()); 
    $file_ending = "xls"; 
    header("Content-Type: application/xls"); 
    header("Content-Disposition: attachment; filename=$filename.xls"); 
    header("Pragma: no-cache"); 
    header("Expires: 0"); 
    $sep = "\t"; 
    $names = mysqli_fetch_fields($result) ; 
    foreach($names as $name){ 

    } 
    print ("dasd" . $sep."dasd1" . $sep); 
    print("\n"); 
    while($row = mysqli_fetch_row($result)) { 
     $schema_insert = ""; 
     for($j=0; $j<mysqli_num_fields($result);$j++) { 
      if(!isset($row[$j])) 
      $schema_insert .= "NULL".$sep; 
      elseif ($row[$j] != "") 
      $schema_insert .= "$row[$j]".$sep; 
      else 
      $schema_insert .= "".$sep; 
     } 
     $schema_insert = str_replace($sep."$", "", $schema_insert); 
     $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert); 
     $schema_insert .= "\t"; 
     print(trim($schema_insert)); 
     print "\n"; 
    } 
?> 
+0

在控制檯中的任何錯誤?你的輸入(來自日期,時間等)是否包含有效數據?你如何在你的'success'回調中打印'responsecon'? –

回答

0

基本上有你jQuery ajax要求兩個問題:

你正在PHP腳本中指定一個內容類型,你必須告訴jQuery在你的ajax對象中使用dataType: application/xls從ajax請求中得到什麼。

這就是爲什麼你沒有得到任何迴應,因爲它失敗了,你沒有指定error回調函數來處理錯誤。

而且,在成功的情況下,你必須以某種方式打印從PHP腳本像$("#selector").html(responsecon);

這裏是更新的AJAX請求返回的內容:

$.ajax({ 
    url: "http://localhost/demo.php", 
    type: "post", 
    dataType: "application/xls", // Tell what content-type to expect from server 
    data: { 
     fromdate:fromdate, 
     ToDate:ToDate, 
     Year:Year, 
     Category:Category 
     }, 
    success: function(responsecon) { 
     window.open('http://YOUR_URL','_blank'); 
     $(#"some-container").html(responsecon); // Print the content 
     }, 
    error: function() { 
     alert("error"); 
     } 
    });