2015-08-08 58 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

你有答案吗?如果是的话,请让我高兴。 –