2013-09-23 26 views
-2

大家好,我是一个网络开发的新学习者。如何使用ajax在后台运行执行页面?

用户点击提交按钮后,我有一个页面,然后按钮将表单内容提交到下一页执行并保存到数据库。

因此,我的页面将转到另一页执行并返回到目标页面。

如:index.php文件和exec.php

的index.php:

<form name="g-form" action="gbtn-exec.php" method="post" class="goat-vote" onsubmit="return validategForm()"> 
<input type="text" name="g-product" placeholder="Brand/Product Name" style="-moz-border-radius: 5px; border-radius: 5px; padding-left:20px; opacity:.5; border:none; margin-left:110px; width:440px; height:38px; font-family:'Proxima Nova Rg';color:#000; font:1.6em;" /> 


<p class="g-question">Why you love it?</p> 

<textarea name="g-reason" style="-moz-border-radius: 5px; border-radius: 5px; padding:5px; opacity:.5; border:none; margin-left:110px; width:450px; height:150px; font-family:'Proxima Nova Rg';color:#333; font-size:1em;"></textarea> 

<input name="g-btn" class="vote-btn" type="submit" value="vote" style="margin-left:470px; cursor:pointer;"></form> 

exec.php

if ($_POST["g-product"] && $_POST["g-reason"] != "") 
{ 
$gproduct = $_POST["g-product"]; 
$greason = $_POST["g-reason"]; 

$insert ="INSERT INTO jovine.vote (vote_id ,product_name ,reason ,type) VALUES (NULL, '$gproduct', '$greason', 'goat')"; 
$result = mysql_query($insert,$con); 
echo "<script>"; 
echo "alert('Thank you. Your vote has been recorded.');"; 
echo "window.location.href='index.php';"; 
echo "</script>"; 
} 

我的问题是,我该如何使用AJAX来运行EXEC .php在后台? 谢谢!

+1

** **危险:您正在使用[**的**过时的数据库API(HTTP://计算器.com/q/12859942/19068),并应使用[现代替换](http://php.net/manual/en/mysqlinfo.api.choosing.php)。你也**易受[SQL注入攻击](http://bobby-tables.com/)**,现代的API会使[防御]更容易(http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php)自己从。 – Quentin

+0

*询问代码的问题必须证明对所解决问题的最小理解。包括尝试解决方案,为什么他们没有工作,以及预期的结果。另请参见:[堆栈溢出问题清单](http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist)* - [教程]不缺(https:// duckduckgo .com /?q = ajax + tutorials) – Quentin

+0

在表单提交处理程序中,防止默认行为并使用ajax调用您的PHP脚本。关于ajax的教程可以很容易找到,不?? –

回答

3

当你标记的jQuery - 只需发送一个HTTP请求到exec.php文件:

$('.vote-btn').on('click', function() { 
    $.ajax({ 
     url: "exec.php", 
     data: { g-product: $('#g-product').val(), g-reason: $('#g-reasons').val() } 
    }).done(function() { 
     alert('Thank you. Your vote has been recorded.'); 
     window.location.href='index.php'; 
    }); 
});