使用jQuery ajax使用GET处理表单和URL [英] Process form and url with GET using jQuery ajax

查看:140
本文介绍了使用jQuery ajax使用GET处理表单和URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用jQuery $ .ajax GET方法处理表单,并在URL中添加查询参数.如果我不使用jquery处理表单,则可以完成此操作,但是如果我通过jQuery的$ .ajax方法执行此操作,则必须使用event.preventDefault()阻止浏览器的默认操作,在这种情况下,参数永远不会以url结尾.基本上,我希望这样做是如果有人从url中键入查询(即mysite.com?param1=myValue)或单击提交按钮,则提交/处理表单.

I'd like to process a form using the jQuery $.ajax GET method and also have the query parameters end up in the url. If I process the form without jquery, I can accomplish this, but if I do it through jQuery's $.ajax method I have to prevent the browser's default action with event.preventDefault(), in which case the parameters never end up in the url. Basically, what I'd like this to do is submit/process the form if someone types in the query from the url (i.e. mysite.com?param1=myValue ) OR if they click the submit button.

<form id='myForm' action="" method="get">
    Username: <input type="text" id="username" name="username" value="" />
    <button id='submitButton' name="">Search</button>
<form>

<script>
 $('#myForm').submit(function(event) {
        event.preventDefault();
        var formData = $(this).serialize(); 
        $.ajax ( {
            url: "myScript.php",
            type: 'GET',
            data: formData,
            success: function (data) {
               console.log(data);
            }
        } );
    });
</script>

myScript.php:

myScript.php:

<?php 
$returnString = array();
$returnString['username'] = $_GET['username'];
echo json_encode($returnString);
?>

推荐答案

构建一个标准按钮(不提交),然后在该按钮的onClick上构建查询字符串并进行ajax调用.这比尝试简化标准表单提交要容易.您的代码已经差不多了.

Build a standard button (not submit), and on the onClick of that button, build your query string and do your ajax call. That's easier than trying to short circuit the standard form submit. Your code is nearly there already.

如果有人手动输入带有参数的url并单击"go",则您的服务器端代码将返回与ajax调用相同的响应,因为服务器不在乎是谁调用它,因此不必担心.我要做的是在ajax调用中添加一个额外的参数,在服务器端,如果存在此参数(这意味着它是从ajax调用的,则数据将返回到现有页面),只需返回json.如果缺少参数(意味着从标准提交调用了该参数),则返回整个html文档,最有可能是同一页面,但dom中已经处理了json.

If someone manually types in a url with parameters and clicks "go", your server side code will return the same response as an ajax call, because the server doesn't care who calls it, so no worries there. What I would do is add an extra parameter to the ajax call, and on the server side, if this param is present (meaning it was called from ajax and data will return to an existing page), just return the json. If the parameter is missing (meaning it was called from a standard submit), return an entire html document, most likely the same page but with the json already processed in the dom.

让服务器端代码去如果是ajax,则返回此代码,否则返回此代码并发送完整的html文档",这是很常见的.

It's pretty common to have server side code go "if it's an ajax, return this, else return this AND a full html document".

这篇关于使用jQuery ajax使用GET处理表单和URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆