是否可以一键提交两个表单?一种形式的值由 JavaScript 生成,另一种形式由 PHP 生成。
我举了一个例子来说明我正在尝试什么。
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<?php
Class testing{
function text_test(){
?>
<form method="post" name="postform">
<input type="textbox" name="text"/>
<input type="submit" onclick ="submit_form()" name="submit"/>
</form>
<?php
}
function display(){
echo $_POST['text'];
echo $_POST['js_input'];
}
}
$test = new testing();
$test->text_test();
if(isset($_POST['js_form'])){
$test->display();
}
?>
<script type="text/javascript">
var jsvariable = "js_test";
</script>
<form method="post" name="js_form">
<input type="hidden" name="js_input" value="document.getElementByName(jsvariable).value" />
</form>
<script type="text/javascript">
function submit_form(){
$('postform').each(function () {
$(this).ajaxForm(); //Initialize as ajaxForm
var options = {
context: this
}
$(this).ajaxSubmit(options); //Submit form with options above
});
$('js_form').each(function () {
$(this).ajaxForm(); //Initialize as ajaxForm
var options = {
context: this
}
$(this).ajaxSubmit(options); //Submit form with options above
});
}
</script>
最佳答案
我不相信连续两次调用 submit() 是不可能的,因为调用 submit() 意味着你正在发出一个 HTTP 请求(GET、POST 等)并且服务器会将你的页面转发到某个地方别的。这意味着永远不会到达第二个 submit()。
最好发送一个阻塞的异步 POST/GET 调用,然后调用 submit() 或什至第二个 POST/GET。
编辑1
请参阅此主题以了解如何 make asynchrnonous GET requests in php . 下一篇引自此源
file_get_contents 会做你想做的事
$output = file_get_contents('http://www.example.com/');
echo $output;
编辑:一种触发 GET 请求并立即返回的方法。
引自http://petewarden.typepad.com/searchbrowser/2008/06/how-to-post-an.html
function curl_post_async($url, $params)
{
foreach ($params as $key => &$val) {
if (is_array($val)) $val = implode(',', $val);
$post_params[] = $key.'='.urlencode($val);
}
$post_string = implode('&', $post_params);
$parts=parse_url($url);
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($post_string)."\r\n";
$out.= "Connection: Close\r\n\r\n";
if (isset($post_string)) $out.= $post_string;
fwrite($fp, $out);
fclose($fp);
}
关于php - php和javascript一键提交多个表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13379663/