te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Why do we need <form> when we have AJAX? - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why do we need <form> when we have AJAX? - Stack Overflow

programmeradmin5浏览0评论

I just started to learn JavaScript, and in my projects I found that wherever a form is used AJAX could be used instead.

A simple example is:

<form id="demo_form" action="demo" method="post">
    <input type="text" name="username">
    <input type="submit" value="Submit">
</form>

And ajax could be used like this:

$('#demo_form input[type="submit"]').click(function(){    
    $.ajax({
        type: "POST",
        url: "/demo",
        dataType: "text",
        data: {
            username: $('#demo_form input[name="username"]').val()
        }
    });
});

And an advantage of ajax is that it could be asynchronous, and I found it really sweet since you can still do something else while waiting for the response from server, and can probably keep the current page and do not lose your input.(when I submit a form, I have to either transfer all inputs to the server and back to the interface all again and just lose them).

Since form is still used and popular nowadays, I guess there are some advantages of it that I do not know.

I just started to learn JavaScript, and in my projects I found that wherever a form is used AJAX could be used instead.

A simple example is:

<form id="demo_form" action="demo" method="post">
    <input type="text" name="username">
    <input type="submit" value="Submit">
</form>

And ajax could be used like this:

$('#demo_form input[type="submit"]').click(function(){    
    $.ajax({
        type: "POST",
        url: "/demo",
        dataType: "text",
        data: {
            username: $('#demo_form input[name="username"]').val()
        }
    });
});

And an advantage of ajax is that it could be asynchronous, and I found it really sweet since you can still do something else while waiting for the response from server, and can probably keep the current page and do not lose your input.(when I submit a form, I have to either transfer all inputs to the server and back to the interface all again and just lose them).

Since form is still used and popular nowadays, I guess there are some advantages of it that I do not know.

Share Improve this question edited Aug 30, 2015 at 2:18 thomasfuchs 1 asked Aug 30, 2015 at 1:16 Justin LiJustin Li 1,1052 gold badges12 silver badges20 bronze badges 5
  • 2 <form> not only has the functionality of a form, but also the semantics because HTML is a semantic language. A form is better than a div nested within dozens of other divs. – Sebastian Simon Commented Aug 30, 2015 at 1:19
  • 3 I will disable all the JS while accessing your site. Than what? no sweet ajax – Abdul Rehman Commented Aug 30, 2015 at 1:21
  • 1 the <form> is used so that you can validate the user's input on the client before submitting it to the server. It's alot better use of resources to make sure that all fields are correct before the form submits data to the server – SuperVeetz Commented Aug 30, 2015 at 1:21
  • @Bsienn fair enough but do that and I bet you'll find that the Ajax not working is the least of your issues...\ – Wesley Smith Commented Aug 30, 2015 at 3:01
  • @SuperVeetz validating inputs is just as easily done with ajax as it is with a form element – Wesley Smith Commented Aug 30, 2015 at 3:02
Add a ment  | 

4 Answers 4

Reset to default 20

First and foremost, the <form> element predates Ajax calls by years. Ajax calls (it's better if you call them XMLHttpRequest) were an addition in Internet Explorer to make it possible to load/post data from JavaScript.

Perhaps most importantly, if you'd stop support either <form> elements or XMLHttpRequest, you'd break basically all existing websites.

Besides the requirement that you need to use JavaScript to issue XMLHttpRequest calls (with JavaScript not always being available), there's also functional and semantic differences:

  • HTML forms semantically group input elements (otherwise, how would you know which input elements belong together?)
  • They support some features like file uploads which until very recently weren't supported in JavaScript at all (you couldn't read the contents of files in file upload fields)
  • Forms know how to serialize input fields (JavaScript libraries like jQuery reimplement this logic that es for free with the browser)
  • Forms aren't affected by CORS restrictions (i.e. they can post to any server; whereas XMLHttpRequest requires special server-side configuration for this)
  • Forms have built-in user interface affordances like submitting on pressing the enter/return key.
  • Forms can post data in different character sets and encodings (via the accept-charset attribute), which is exceedingly difficult to do in JavaScript (in JavaScript all strings are Unicode)

XMLHttpRequest of course can do things that forms can't, for example set HTTP headers, can use more HTTP verbs (not only post and get), as you mentioned can be asynchronous and they also have a hugely expanded range of events you can react to.

Both technologies have their place, depending on what you'd like to achieve.

There's the case of providing functionality for users when JavaScript is not available. That and also realizing that some actions that we proxy over JavaScript like PUT and DELETE can't be done using <form> without proxying a hidden input like <input type=hidden name=_method>.

There's a one major advantage that nobody mentioned so far - dynamic data population. Having only one field in the form, you wouldn't probably feel that.

But consider a form, that has several fields:

<input type="text" name="qty" />
<input type="text" name="price" />
<input type="text" name="title" />
... and so on ...

And you would populate data this way:

data : {
  price : $("[name='price']").val(),
  qty : $("[name='qty']").val(),
  title : $("[name='title']").val(),
}

And what If decide to add more fields later? You'd have append new field names with their values to data. And as your code grows, it would get messy quite fast.

Instead, you'd better stick to form serialization. The above can be simply rewritten as:

data : $("form").serialize()

And even if you add more fields later, you don't have to populate data anymore. In simple words, $("form").serialize() makes population of data dynamically.

This answer may be better explained by someone with much more experience, but I'll give it a try:

Forms were created as part of HTML, as a way to send information from the browser to a server URL (the action attribute) waiting to do something with that information. Then, as part of JavaScript, it was created dynamic calls to the server (Asynchronous calls to be more specific). Those are probably more known today, but before it forms with actions were the way to solve that use case.

发布评论

评论列表(0)

  1. 暂无评论