2015-01-13 180 views
1

我的表單將多個文本字段和一個文件上傳到php腳本來保存文件並將文本字段保存到sql db。這是工作,我的PHP腳本結束jquery ajax請求不返回到頁面

   ('state' => 200, "success" => true, "id" => $_POST['id'], "titlea" => $_POST['title'], "addressa" => $_POST['address'], "lot_sizea" => $_POST['lot_size'], "zoninga" => $_POST['zoning'], "build_sizea" => $_POST['build_size'], "sale_pricea" => $_POST['sale_price'], "lease_pricea" => $_POST['lease_price'], "commenta" => $_POST['comment'], "transactiona" => $_POST['transaction'], "ad_linka" => $ad_link, 
      ); 
    exit(json_encode($response)); 

這是返回一個JSON編碼的響應。然而,返回留在php頁面上,並不會回到帶有ajax請求的頁面。這裏是我的ajax腳本:

$("document").ready(function() { 
    $(".data-form").submit(function() { 
     var formData = new FormData($('form')[0]); 
     if (confirm("\t\t\tAre you ready to sumbmit this listing?\nYou can always edit the listing after going to the menu tab - edit listing.")) { 
      $.ajax({ 
       type: "POST", 
       dataType: "json", 
       url: "add-list.php", 
       data: formData, 

       success: function(response) { 
        if (response.success) { 
         $("#modal1").modal('hide'); 
         $("#add_frame").show(); 
         $("#newbutt").show(); 
         $(".atitle").html('<a href="' + response.ad_linka + '" target="_blank">' + response.titlea + '</a>'); 
         $(".acomment").html(response.commenta); 
         $(".aaddress").html(response.addressa); 
         $(".asale-price").html(response.sale_pricea); 
         $(".alease-price").html(response.lease_pricea); 
         $(".alot-size").html(response.lot_sizea); 
         $(".abuilding-size").html(response.build_sizea); 
         $(".azoning").html(response.zoninga); 
        } else { 
         console.log("An error has ocurred: sentence: " + response.sentence + "error: " + response.error); 
        } 
       }, 
       error: function() { 
        alert("An Error has ocurred contacting the server. Please contact your system administrator"); 
       } 
      }); 
      return false; 
     } 
    }); 
}); 

我該如何改變這個,以便我可以返回頁面並允許成功方法運行?

這裏是我的開端:

<form class="avatar-form" enctype="multipart/form-data" method="POST"> 
+0

評論是不適合擴展討論;這個對話已經[轉移到聊天](http://chat.stackoverflow.com/rooms/68768/discussion-on-question-by-rhillz-jquery-ajax-request-not-returning-to-page)。 –

回答

2

夫婦的問題:

首先,你需要確保你選擇了正確的形式。 $('form')將選擇所有表格,並且$('form')[0]將選擇第一個。你應該改爲正確的形式。

$('.data-form')[0] 

接下來,發送FormData時,必須將processData和contentType設置爲false,以便jQuery不會嘗試處理FormData。 (這是內$.ajax({...})完成)

contentType: false, 
processData: false 

注:AJAX文件上傳將不能在IE


這也是一個很好的做法(至少在調試)使用event.preventDefault工作,而不是返回false,並在處理程序頂部執行此操作,以便如果發生任何語法錯誤,您的表單將不會提交,從而無法查看錯誤。以普雷斯頓S的答案爲例。