提交表单值而不加载新页面


Submit form values without loading a new page

我有一个表单,我用它来传递值到另一个页面和它的工作。

有没有办法做到这一点,而不打开一个页面,我的表单动作设置?

我认为可以使用ajax和javascript

echo "<form name='"android'"  method='"post'" action='"http://www.example.com'" target='"_blank'">";
echo "<input type='"hidden'" name='"appid'" value='"$appid'" />";
echo "<input type='"hidden'" name='"pushmessage'" value='"$pushmessage'" />";
echo "<input type='"hidden'" name='"username'" value='"$user'" />";
echo "<input type='"hidden'" name='"pass'" value='"$pass'" />";
echo  "<input type='"hidden'" name='"publisherid'" value='"createcoolapps'" />";
//echo "<input type='"submit'" value='"Push'" name='"sub'" />";
echo "</form>";
echo "<script> document.forms[0].submit();</script>";

试试这个:

$url = 'http://www.example.com/';
$fields = array(
    'appid' => urlencode($appid),
    'pushmessage' => urlencode($pushmessage),
    'username' => urlencode($user),
    'pass' => urlencode($institution),
    'publisherid' => urlencode("createcoolapps")
);
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
curl_close($ch);

是的,正如您所想的那样,这可以使用Ajax完成。到目前为止,最简单的方法是使用jQuery的AJAX库(因为如果没有别的,谁现在不使用jQuery): http://api.jquery.com/jQuery.ajax/

一个例子可能如下(未经测试,但有点正确):

<form action="mypage.php" method="post"> <!-- Args for when JS is disabled -->
    <input type="text" id="form_text_1" value="" />
    <input type="submit" id="form_submit" />
</form>
<script>
    $('#form_submit').click(function() {
        jquery.ajax("mypage.php", {
            type: "post",
            data: {
                text1: $('#form_text_1').val()
            }
        });
        return false; // Stop the form being submitted in the foreground when JS works
    });
</script>

当然,根据你的需要调整。

如果你能包含jQuery库,这是非常容易的:http://www.jquery.com

如果您使用jQuery和上面的代码,您可以执行以下操作:

$('input[name="sub"]').click( function() {
   $.post($(this).parents('form').attr('action'), $(this).parents('form).serialize());
   return false;
} );

这拦截了名为"sub"的提交的点击,然后执行AJAX post到表单的动作。

您最好查看您的浏览器控制台,以跟踪发布的数据并发现任何问题。