2011-02-06 39 views
0

我是Ajax的新手,目前使用php和ajax(用于wordpress插件)进行表单提交。我的js代码是Ajax请求返回页面的每个html元素

$("#submit").click(function(){ 
var form_data = $('.myform').serialize(); 
$.ajax({ 
    type: "POST", 
    url: "main_form.php", 
    data: form_data, 
    success: function(html){ 
    $('div#ajax_output').html(html); 
    }      
}); 
return false; 
    }); 

和我的整个页面结构看起来像

<div class="header"> ....</div> 
<div class="navigation"> ....</div> 
< ?php 
if($_post) { 
    //form validation codes 
    if(condition true) echo "Success message"; 
    else echo "Error"; 
} 
?> 
<div id="ajax_output"></div> 
<form class="myform"> 
    //form elements 
</form> 
//And the above javascript here(that click fn) 

现在我的问题是,因为我提交表单数据到同一个页面(这是不可避免的,不能使其分开),ajax返回<div id="ajax_output"></div>里面所有的页面内容头,导航等包括echo“Success message”。 任何人可以告诉我如何只输出PHP验证结果?

+0

尝试包括一个网页,只得到了结果...显示该网页不是头,菜单等......只有开结果。 – Thew 2011-02-06 11:23:06

+0

对不起,你错了,可能是因为我英语不好。 ajax返回页面中的所有html元素(头文件,导航等),而只返回php验证结果。结果,点击提交按钮后有两个标题,两个导航元素。 – devdarsh 2011-02-06 11:37:23

回答

1

输出缓冲可以帮助你

<?php // insert that at the beginning of the page 
    ob_start(); 
?> 
<div class="header"> ....</div> 
<div class="navigation"> ....</div> 
<?php 
if($_post) { 
    //form validation codes 
    if(condition true) echo "Success message"; 
    else echo "Error"; 
    ob_end_clean(); 
    exit(1); 
} else { 
    echo ob_get_clean(); 
} 
?> 
<div id="ajax_output"></div> 
<form class="myform"> 
    //form elements 
</form> 
//And the above javascript here(that click fn) 

你最好重构代码,虽然。即将发布数据的处理移动到页面的开头,然后在应该处理时退出。

通常,这些问题在服务器端解决,而不是在javascript中解决。 我的意思是,服务器应该返回正确的HTML部分W/O标题,导航等,客户端不应该解析所有的东西,以得到它所需要的东西。

0

您可能会在检查表单数据之后返回,或者在另一个操作中执行表单验证。

0

该代码示例不完整,但您可以获得它的希望! 添加一个变量来发布数据。

的Javascript:

$("#submit").click(function(){ 
    var form_data = $('.myform').serialize(); 

    form_data.isAjax = true; 

    $.ajax({ 
     type: "POST", 
     url: "main_form.php", 
     data: form_data, 
     success: function(html){ 
     $('div#ajax_output').html(html); 
     }      
    }); 
    return false; 
}); 

PHP:

<?php 

if(array_key_exists("isAjax", $_POST) { 
    if($_post) { 
     //form validation codes 
     if(condition true) { 
     echo "Success message"; 
     } 
     else { 
     echo "Error"; 
     } 
    } 
} 
else { 
    $mainPage = '<div class="header"/>>'; 
    $mainPage += '<div class="navigation"/>'; 
    $mainPage += '<div id="ajax_output"/>'; 
    $mainPage += '<form class="myform"/>'; 
    $mainPage += '<javascript />'; 

    echo $mainPage; 
}