dongpo5239 2014-04-24 17:01
浏览 76
已采纳

最简单的表单提交没有重定向?

So I have been killing myself on this project, maybe because I tried doing it the hard way :) I have been trying to convert the following dynamic PHP form to be submitting the same info, but via AJAX which I have no experience in, but I wanted to submit without leaving the page.

While researching "Things Every PHP Coder Should Know" (http://terrychay.com/article/php-coders.shtml) while preparing to phone interview a potential programmer, I was introduced a different method of accomplishing the same task using remote scripting and an iframe. Realizing there could be dozens of ways of doing this, what would be the "best" way to take the following form, and submit it without leaving the page? Since I know PHP best, is there one that would be better suited to me or should I keep going with AJAX?

<form action="functions.php?do=save" method="POST" id="saveSettings">
<table width=100%>
<tr><th>Setting</th><th>Value</th><th>Active</th></tr>
<?
include 'db.php';

$i=0;
    foreach($db->query('SELECT * from settings') as $row) {
    echo ($i % 2)?'<tr class="odd">':'<tr class="even">';
        print_r("<td width=200>" . $row[1] . "</td>
        <td><input type=\"textbox\" name=\"" . $row[1] . "[]\" value=\"" . $row[2] . "\"></td> 
        <td><input type=\"hidden\" name=\"" . $row[1] . "[1]\" value=\"INACTIVE\"> "); //set value so it never passes NULL
            if ($row[3] == "ACTIVE"){
            print_r("<input type=\"checkbox\" name=\"" . $row[1] . "[1]\" value=\"ACTIVE\" checked=\"true\"></td></tr>");
            }
            else{
            print_r("<input type=\"checkbox\" name=\"" . $row[1] . "[1]\" value=\"ACTIVE\"></td></tr>");

            }
    $i++;
    }
?>
</tbody>
</table>
<input type="submit" value="Save Settings">
</form>
  • 写回答

1条回答 默认 最新

  • dongqing5575 2014-04-24 17:03
    关注

    It's quite simple, really, all you need to do is the following jQuery:

    $('form').on('submit', function(){
        var $this = $(this);
        $.ajax({
            type: $this.prop('method'),
            url: $this.prop('action'),
            data: $this.serialize(),
            success: function(data){
              //do something with the return of the php script
            }
        });
        return false; //prevent the form from causing the page to refresh
    });
    

    $.serialize() is used to turn the form into a text string that is URL encoded. This makes it simple to get the values in the php script as nothing should change given the structure of your form above.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题