2015-08-08 36 views
1

所以我得有「create_topic_parse.php」的動作形式,它發送的輸入值,從「create_topic.php」,然後他們被插入到數據庫中。我可以使用下面的代碼從「create_topic_parse.php」文件發送任何錯誤「消息」格在我的「create_topic.php」頁:停止jQuery的從返回整個頁面到我的div

$("#submit").click(function() { 
// I've tried e.preventDefault(); here^but it's giving the same result. 

     $.post($("#topic_form").attr("action"), 
      $("#topic_form :input").serializeArray(), 
      function(info) { 

       $("#message").empty(); 
       $("#message").html(info).css('color','#be4343'); 

      }); 

    $("#topic_form").submit(function() { 
     return false; // Not working 

    }); 
}); 

當表單是正確輸入,並且沒有錯誤要從PHP文件傳遞,PHP腳本應該將用戶重定向到'view_topic.php?cid =「。$ cid。」 & tid =「。$ new_topic_id。」 & page = 1'。如果我不包含上面的jQuery,這工作正常。

問題:如果我包括jQuery腳本,它返回整個'view_topic.php/etcetc'頁進',這是不好的。

所以現在的問題是,沒有人知道如何防止整個頁面被投遞到這個div,居然將用戶重定向到「view_topic.php頁面表單時正確提交?

注意:我試過window.location,但是我已經從我的PHP文件輸入'view_topic.php/etcetc'url中的concatonated變量的問題。我試圖讓它與標題('location:...')一起工作,就像它沒有包含jQuery文件時一樣。

由於提前,

裏奇

解決方案:

的jQuery + Ajax技術PHP:

if($('#topic_title').val() == ''){ 
    $('#message').html("You need to give your topic a title."); 
} 

使用此代碼,我能夠檢查是否每個數據條目存在,當所有的數據值都存在時,我會在同一個文件中運行AJAX腳本,將每個值傳遞給va像可變結構如此:

var submit = $('#submit').val(); 
var topic_title = $('#topic_title').val(); 


$.ajax({ 
     type: "POST", 
     url: "create_topic_parse.php", 
     data: {submit:submit, topic_title:topic_title), 

等等等等

+0

我認爲'window.location ='view_topic.php''但是有什麼問題呢?你能否詳細說明或通過代碼展示這種鬥爭是什麼? – Rasclatt

+0

我將表單提交時由PHP腳本給出的變量鏈接到我的頭文件中('location ...)。一切都進入數據庫。 –

+0

在你的php頁面上,你應該使用'echo json_encode($ array_with_variables)'將這些變量回顯到json字符串中,然後當你的當前頁面接收到字符串時,它會將json數組解析爲一個對象,然後使用'window .location ='view_topic.php?cid ='+ Parsed.cid +'&tid ='+ Parsed.tid +'&page = 1'',您當前的窗口將使用正確的變量重新加載到您的$ _GET中。 – Rasclatt

回答

0

試試這一個。它會工作 當表單正確提交然後只發送一些像「正確」的字符串,並在jquery讓你檢查輸出字符串。如果它是「正確的」,那麼將其重定向到通過javascript查看主題。

,如果你想將用戶重定向到從服務器發送一個特定的頁面,然後從JSON格式的服務器是這樣的發送。在服務器上像這樣

寫代碼。 create_topic.php頁

$("#topic_form").submit(function(e) { 
     e.preventDefault(); 
     $.post( 
      $("#topic_form").attr("action"), 
      $("#topic_form :input").serializeArray(), 
      function(info) { 
        info= JSON.parse(info);      
        if(info.message="correct"){ 
         window.location=info.url; 
        } 
        else{ 
         $("#message").html(''); 
         $("#message").html(info).css('color','#be4343'); 
        } 

      }); 

}); 

if ($condition==true) { 
    $ajax_return = array(
     'message' => 'correct', 
      'url' => 'your_redirect_url' 
    );   
} 
else 
{ 
    $ajax_return = array(
     'message' => 'your user defined error message', 
     'url' => 'leave it blank' 
    ); 
} 
$ajax_return = json_encode($ajax_return); 
echo $ajax_return; 

,現在的jQuery我敢肯定,現在它會工作。如果沒有,請告訴我。

+0

謝謝,但是當提交成功時,我恐怕它仍然返回'('#message')div'view_topic.php?cid =「。$ cid。」&tid =「。$ new_topic_id。」&page = 1'。 –

+0

只是在烹飪晚餐atm,但我會盡快嘗試。謝謝你的堅定迴應。我會讓你知道它是怎麼回事。 –

+0

你有答案嗎?如果是的話,請讓我高興。 –