如何在没有ajax的情况下以良好的方式获得表单动作响应?

发布于 2024-09-26 11:06:03 字数 1554 浏览 2 评论 0原文

我知道如何获得 AJAX 响应:

$.post( '/action', 
        { actiontodo: 'insert' } 
        function (data) { alert(data); } );

Int the action.php(服务器端):

<?php 
       if ($_POST['actiontodo'] == 'insert') 
       { 
           doInsertAction(); 
           echo "inserted"; 
       } 
?>

最后,此代码的输出是一个带有单词:inserted 的警报框。

但是,如果没有ajax,我有两种方法来解决这个问题(在服务器端):

一个:

<?php 

if ($_POST['actiontodo'] == 'insert') { 
    doInsertAction(); 
    header( "Location: " . $_SERVER['HTTP_REFERER'] . " &response=inserted"  ); 
} ?>

两个:

<?php
session_start();
if ($_POST['actiontodo'] == 'insert') {
    doInsertAction();
    $_SESSION['response'] = 'inserted';
}
header( "Location: " . $_SERVER['HTTP_REFERER'] );
?>

返回页面,我从 SESSION 或从获取并显示警报。

我更喜欢“单一”解决方案,但每个解决方案都有一个问题:

一个问题:

返回的 URL 是:http://www.foo.com/myrefererurl&response=inserted

如果您在不使用表单的情况下键入此 URL,则每次刷新页面时您都会看到警告框。问题是:如何仅显示该消息一次? (仅在表单操作之后)

两个问题:

SESSION 现在已插入值 ($_SESSION['response']),当页面从操作返回时,显然解决方案可能会删除该值会话如: unset( $_SESSION['response'],但假设由于任何原因(连接失败或导航被用户停止等)未达到 UNSET,当您转到其他页面中的另一个表单时,警报将显示,因为$_SESSION['response'] 仍然存在(以另一种形式提交,并且与该响应无关)。包含在另一个 URL 中插入的 GET &response= 问题也将存在

。并提出最好的解决方案,基本上问题是如何控制这种反应......

I know how to get an AJAX response:

$.post( '/action', 
        { actiontodo: 'insert' } 
        function (data) { alert(data); } );

Int the action.php (server side):

<?php 
       if ($_POST['actiontodo'] == 'insert') 
       { 
           doInsertAction(); 
           echo "inserted"; 
       } 
?>

Finally the output of this code is an alert BOX with the word: inserted.

BUT, without ajax, I have two ways to solve this (in the server side):

ONE:

<?php 

if ($_POST['actiontodo'] == 'insert') { 
    doInsertAction(); 
    header( "Location: " . $_SERVER['HTTP_REFERER'] . " &response=inserted"  ); 
} ?>

TWO:

<?php
session_start();
if ($_POST['actiontodo'] == 'insert') {
    doInsertAction();
    $_SESSION['response'] = 'inserted';
}
header( "Location: " . $_SERVER['HTTP_REFERER'] );
?>

Returning to the page I get the answer from the SESSION or from GET and shows the alert.

I like more the ONE solution, but each solution has a problem:

ONE problem:

The returning URL is : http://www.foo.com/myrefererurl&response=inserted

If you types this URL without using the form, you will see the alert BOX each time you will refresh the page. The question is: How to show the message only ONE time? (ONLY AFTER THE FORM ACTION)

TWO problem:

The SESSION now has the value inserted ($_SESSION['response']), when the page returns from the action obviously the solution maybe delete this value of the session like: unset( $_SESSION['response'], but SUPPOSE the UNSET do not reached for any reason (connection failure or navigation stopped by the user, etc), when you go to another form in other page the alert will showed because the $_SESSION['response'] still exists (in another form without submit it and has nothing to do with that response). Inclusively WITH GET &response=inserted in another URL the problem will exists too.

I hope you understand this questions and bring a BEST WAY solution. Basically the question is how to control that responses......

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蒗幽 2024-10-03 11:06:03

不引人注目的 JS,或“渐进式增强”是正确的选择。

第 1 步:

首先构建无需 JavaScript 即可运行的页面。假设您有一个简单的应用程序,用户选择某些内容并点击提交。根据选择,您将在表单上方显示有用的错误消息,或者使用正确的输出更新页面并隐藏(或删除)表单。像构建 AJAX 一样构建此页面,但不要编写任何脚本。

这是您的页面:

<html>
<head>
    <style type="text/css">
        p#feedback { display:none;}
    </style>
</head>
<body>
    <div id="feedback"></div>
    <div id="form">
        <form action="getaction.php" method="post" id="actionform">
            <select name="requestedAction">
                <option value="foo">Do Foo</option>
                <option value="bar">Do Bar</option>
            </select>
            <input type="submit">
        </form>
    </div>
</body>
</html>

成功提交。服务器将收到带有一个 $_POST 值的请求:requestedAction=foo(或 bar)。基于此,您的服务器脚本将构造一个新页面,其中包含从 的所有内容。

此时,您已经有了一个可以在任何不支持 JS 的浏览器中运行的页面。老式的。非常可靠。

第 2 步

添加脚本以覆盖默认的提交 行为。从页面中获取所需的数据并构建 AJAX 提交。这与上面的提交之间的唯一区别是,您将添加一个标志,告诉服务器请求是通过 AJAX 发出的,并仅发回所需的消息(您也可以将其发送到不同的脚本)。服务器脚本基本上将执行与上面相同的逻辑,但它不会构建整个页面,而是仅发送回消息字符串并将其留给 AJAX 以将该数据放在正确的位置。您的响应可以只是一个文本片段、一个 HTML 块或一个 XML 数据结构。这取决于您的需求。

<script type="text/javascript">
    $(enhance); // at onDOMReady, run the enhance function

    function enhance() {
        // Override the default form submission behavior:
        $('form#actionform').bind('submit',doSubmit);
    };
    function doSubmit(event) {
        $.ajax(
            {
                type:'POST',
                url:'/path/to/getaction.php',
                data:'request=' + $('form#actionform select[name=requestedAction]').val() + '&type=ajax',
                success:fnCallback
            }   
        );
        // Kill the submit action so the user doesn't leave the page
        event.preventDefault();
    };
    function fnCallback(xhr) {
        var strResponse = xhr.responseText; 
        if (strResponse === "error") {
            $('div#feedback').text("There was an error. Please try again.");
        }
        else {
            $('div#feedback').text(strResponse);
            $('div#form').hide();
        }
    };
</script>

在这种情况下,服务器将可以识别 AJAX 提交,因为有第二个 POST 参数 type=ajax

ESPN 是一个在规模上做得非常出色的网站。关掉JS,在大局下查看他们的主要故事标题。该行为与他们启用 AJAX 的页面相同,除了视频无法正常工作之外,您真的永远不会知道您的 JS 是打开还是关闭。如果不从愚蠢的 HTML 开始并逐步构建,基本上就无法构建这样的网站。

Unobtrusive JS, or "progressive enhancement" is the way to go.

Step 1:

Build your page first to work without JavaScript. Let's say you have a simple application where a user selects something and hits submit. Depending on the selection, you will either display a helpful error message above the form or you'll update the page with the correct output and hide (or get rid of) the form. Build this page like you would for AJAX, but do not script anything yet.

Here's your page:

<html>
<head>
    <style type="text/css">
        p#feedback { display:none;}
    </style>
</head>
<body>
    <div id="feedback"></div>
    <div id="form">
        <form action="getaction.php" method="post" id="actionform">
            <select name="requestedAction">
                <option value="foo">Do Foo</option>
                <option value="bar">Do Bar</option>
            </select>
            <input type="submit">
        </form>
    </div>
</body>
</html>

On a successful submission. the server will get a request with one $_POST value: requestedAction=foo (or bar). Based on this, your server script will construct a new page with everything from <html> to </html>.

At this point, you have a page that works in any non-JS-enabled browser. Old fashioned. Very reliable.

Step 2

Add the scripting to override the default submit behavior. Grab the data you need from the page and construct an AJAX submission. The only difference between this and the submission above is that you will add a flag telling the server that the request is coming via AJAX and to send back only the needed message (you could also send it to a different script). The server script will basically go through the same logic as above, but rather than building the entire page, it only sends back the message string and leaves it to AJAX to put that data in the right place. Your response could be just a text fragment, a block of HTML or an XML data structure. It depends on your needs.

<script type="text/javascript">
    $(enhance); // at onDOMReady, run the enhance function

    function enhance() {
        // Override the default form submission behavior:
        $('form#actionform').bind('submit',doSubmit);
    };
    function doSubmit(event) {
        $.ajax(
            {
                type:'POST',
                url:'/path/to/getaction.php',
                data:'request=' + $('form#actionform select[name=requestedAction]').val() + '&type=ajax',
                success:fnCallback
            }   
        );
        // Kill the submit action so the user doesn't leave the page
        event.preventDefault();
    };
    function fnCallback(xhr) {
        var strResponse = xhr.responseText; 
        if (strResponse === "error") {
            $('div#feedback').text("There was an error. Please try again.");
        }
        else {
            $('div#feedback').text(strResponse);
            $('div#form').hide();
        }
    };
</script>

In this case, the AJAX submission will be identifiable to the server because there is a second POST parameter of type=ajax.

A site that does this really unbelievably well on a very big scale is ESPN. Turn off JS and check out their main story headlines under the big picture. The behavior is identical to their AJAX-enabled page and aside from the video not working, you really would never know if your JS was on or off. There's basically no way to build a site like this without starting from dumb HTML and building up.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文