【问题标题】:Submitting basic form data with AJAX to PHP web service使用 AJAX 向 PHP Web 服务提交基本表单数据
【发布时间】:2016-01-20 13:49:27
【问题描述】:

我正在尝试使用 jQuery / Ajax 将一些表单数据提交到 PHP Web 服务(php 文件)并简单地回显结果。

这是我的 index.html 文件

<html>
<head>
<title>PHP web service &amp; AJAX</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>

<body>
    <h1>Hello! Is it me you're looking for?</h1>

    <form id="submit">
        <label>Name</label>
        <input id="name" type="text" name="name" />
        <label>Email</label>
        <input id="email" type="email" name="email" />
        <input class="submit" type="submit" value="Submit details" />
    </form>

    <script type="text/javascript">
        $(document).ready(function(){
            $(".submit").click(function(e) {
                e.preventDefault();

                // BUILD DATA STRING
                var name = $("#name").val();
                var email = $("#email").val();
                var dataString = "subName=" + name + "&subEmail=" + email;

                $.ajax({
                    type: 'POST',
                    url: 'results.php',
                    data: dataString,
                    success: function() {
                        window.location.href = "results.php";
                    }
                });
            });
        });
    </script>

还有 PHP (results.php) 文件

<?php
    echo $_POST['subName'] . "<br />" . $_POST['subEmail'];
?>

到目前为止没有运气,有人可以帮助我吗?我也尝试过this tutorialthis one,但它们没有帮助。

【问题讨论】:

  • 去掉window.location.href = "results.php";,使用AJAX时不需要。它会在成功完成 AJAX 后重定向页面,给人的印象是 AJAX 不起作用并且表单已提交并重定向
  • @Tushar 我可以将成功函数留空,脚本就可以了吗?
  • 是的,使用success: function(response) { console.log(response); },
  • 我也会推荐使用data: $('form').serialize(),

标签: javascript php jquery html ajax


【解决方案1】:

观看这个精彩的视频,亚当先生以非常简单明了的方式解释了所有基础知识。您甚至不必使用第三方 JS 库来完成这项工作。

此代码接受来自表单的值,对其进行处理,并通过 Javascript 返回客户端的 HTML

链接:- Return data from PHP with AJAX

源代码: Source code of video

index.html

<html>
    <head>
        <script>
            function ajax_post(){
                // Create our XMLHttpRequest object
                var hr = new XMLHttpRequest();
                // Create some variables we need to send to our PHP file
                var url = "my_parse_file.php";
                var fn = document.getElementById("first_name").value;
                var ln = document.getElementById("last_name").value;
                var vars = "firstname="+fn+"&lastname="+ln;
                hr.open("POST", url, true);
                // Set content type header information for sending url encoded variables in the request
                hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                // Access the onreadystatechange event for the XMLHttpRequest object
                hr.onreadystatechange = function() {
                    if(hr.readyState == 4 && hr.status == 200) {
                        var return_data = hr.responseText;
                        document.getElementById("status").innerHTML = return_data;
                    }
                }
                // Send the data to PHP now... and wait for response to update the status div
                hr.send(vars); // Actually execute the request
                document.getElementById("status").innerHTML = "processing...";
            }
        </script>
    </head>
    <body>
        <h2>Ajax Post to PHP and Get Return Data</h2>
        First Name: <input id="first_name" name="first_name" type="text">  <br><br>
        Last Name: <input id="last_name" name="last_name" type="text"> <br><br>
        <input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br>
        <div id="status"></div>
    </body>
</html>

my_parse_file.php

<?php 
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>

【讨论】:

    【解决方案2】:

    在成功处理程序中,您要捕获 ajax 调用返回的 data,然后使用 $('#results').html(data) 在页面上输出它。此外,如果需要,您希望使用$('#submit').hide() 隐藏表单。您的代码应如下所示:

    $(document).ready(function () {
        $("#submit").on('submit', function (e) {
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: 'results.php',
                data: $(this).serialize(),
                success: function (data) {
                    $('#results').html(data);
                    //$('#submit').hide();
                }
            });
        });
    });
    

    那么你应该在你的页面中添加以下div

    <div id="results">Results will go here</div>
    

    【讨论】:

    • 我明白了。逻辑刚刚点击。谢谢。
    【解决方案3】:

    使用您的代码,您实际上并没有寻找 results.php 的输出,即使您是,您也只是将用户重定向到页面(这也不会 POST 任何数据) .

    你想做的是这样的:

    $.ajax({
        type: 'POST',
        url: 'results.php',
        data: dataString,
        success: function(data) { //where "data" is the output of results.php
            alert(data); //will bring up an alert box with subName and subEmail
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2012-07-11
      • 1970-01-01
      • 2014-08-07
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      • 2013-12-12
      • 1970-01-01
      相关资源
      最近更新 更多