简体   繁体   English

通过AJAX在与文件相同的文件中调用表单数据处理PHP <form> ?

[英]Form-data-processing PHP called via AJAX in same file as <form>?

When you use HTML forms, I learned it's 'elegant' to process the data in the same file eg. 当您使用HTML表单时,我了解到处理同一文件中的数据是“优雅的”,例如。 <?php if isset($_POST['submit'] doSomething(); ?> ... <form action="" method="POST">

But what if I want to send the data via ajax? 但是,如果我想通过ajax发送数据怎么办? Do I put the doSomething() in a separate php-file that I send the data to or should I also put it in the same file and just exit() before the actual site content begins (if it has been called by ajax)? 我应该将doSomething()放在发送数据的单独的php文件中,还是应该将其放在同一文件中,然后在实际站点内容开始之前就exit() (如果它已被ajax调用)? I think that way it would be a lot easier to make the site also work with JS disabled. 我认为通过这种方式,使网站在禁用JS的情况下也可以轻松得多。

I understand that both ways would work, but I'm wondering what's considered cleaner and will lead to less errors. 我知道这两种方法都行得通,但是我想知道哪种方法更干净,并且可以减少错误。

Here's example code to explain what I mean: 这是解释我的意思的示例代码:

/* example.php */
<?php
if( isset( $_POST['submit'] ) ) {
    doSomething( $_POST['foo'] );
    if( !isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
        exit();
    }
}
?>
<html>
    <head>
    ...
    </head>
    <body>
        <form action="" method="POST">
            <input type="text" name="foo" id="foo">
            <input type="submit" name="submit">
        </form>
    <script type='text/javascript'>
    $('form').submit( function( event ) {

        event.preventDefault();

        $.post( 'example.php', { submit: '', foo: $('#foo').val() } );

    } );
    </script>
    </body>
</html>

Is that a good and maintainable approach? 这是一个好的且可维护的方法吗?

Yeah as you've said both options will work. 是的,正如您所说的,两种选择都可以使用。 But best practice is to use seprate file for AJAX calls, they are called as Web services/APIs. 但是最佳实践是对AJAX调用使用单独的文件,它们被称为Web服务/ API。

They are made for doing some specific tasks. 它们是为执行某些特定任务而设计的。

So create new file for AJAX request and perform a single specific task from this file and return appropriate data as JSON/HTML. 因此,为AJAX请求创建新文件,并从该文件执行单个特定任务,然后以JSON / HTML格式返回适当的数据。

This way you keep the main file's logic and form's logic separate and there won't be chaos in main PHP file. 这样,您可以将主文件的逻辑和表单的逻辑分开,并且主PHP文件中不会出现混乱。

When you use HTML forms, I learned it's 'elegant' to process the data in the same file 当您使用HTML表单时,我了解到处理同一文件中的数据是“优雅”的

Not really. 并不是的。 It's a good idea to process the data on the same URL . 在相同的URL上处理数据是一个好主意。

The primary advantage of this is that when users submit bad data, it allows you to easily show the form again, prepopulated with the data from the last attempt, and with additional error messages. 这样做的主要优点是,当用户提交错误的数据时,它使您可以轻松地再次显示该表单,并使用上次尝试的数据以及其他错误消息进行预填充。

Putting everything into a single file isn't such a good idea. 将所有内容放入单个文件并不是一个好主意。 It's generally better to split things up. 通常最好将其拆分。 For example: 例如:

include("process_form_data.php");
include("form.php");
include("result.php");

$errors = array();

if ($_POST['submit']) {
    $errors = process_form_data();
    if (count($errors)) {
         show_form();
    } else {
         show_result();
    }
} else {
    show_form();
}

This is usually simplified by the use of an MVC framework of similar. 通常,通过使用类似的MVC框架可以简化此过程。


But what if I want to send the data via ajax? 但是,如果我想通过ajax发送数据怎么办?

Then it matters less. 然后,事情就不那么重要了。 You never need to show the whole form in response to the Ajax request. 您无需响应Ajax请求就显示整个表单。 The response is more likely to be a JSON dump of $errors or the result information. 响应更有可能是$errors或结果信息的JSON转储。

Since the logic is stored in include files you can put it on a separate URL and still get easy access to all the shared logic. 由于逻辑存储在包含文件中,因此您可以将其放在单独的URL上,并且仍然可以轻松访问所有共享逻辑。

That said, it would be a little more RESTful to use the same URL and add an addition bit of if/else to do different things based on the Accept header (ie test to see if JSON is prefered over HTML as the response). 就是说,使用相同的URL并添加更多if/else来基于Accept标头做不同的事情(即测试以查看是否优先使用JSON作为HTML响应来测试JSON)会更加RESTful。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM