使用 PHP 的 jQuery Ajax POST 示例

jQuery Ajax POST example with PHP

提问人:Thew 提问时间:2/15/2011 最后编辑:Kamil KiełczewskiThew 更新时间:11/8/2022 访问量:1813996

问:

我正在尝试将数据从表单发送到数据库。这是我使用的表格:

<form name="foo" action="form.php" method="POST" id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>

典型的方法是提交表单,但这会导致浏览器重定向。使用jQuery和Ajax,是否可以捕获表单的所有数据并将其提交到PHP脚本(例如form.php)?

javascript jquery ajax post

评论

4赞 TRiG 1/8/2013
请参阅相关的元讨论,了解取消删除背后的原因。
1赞 leonheess 1/13/2020
简单的 vanilla js 解决方案:stackoverflow.com/a/57285063/7910454

答:

1022赞 21 revs, 9 users 73%mekwall #1

.ajax 的基本用法如下所示:

HTML格式:

<form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />

    <input type="submit" value="Send" />
</form>

j查询:

// Variable to hold request
var request;

// Bind to the submit event of our form
$("#foo").submit(function(event){

    // Prevent default posting of form - put here to work in case of errors
    event.preventDefault();

    // Abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);

    // Let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "/form.php",
        type: "post",
        data: serializedData
    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

});

注意:从 jQuery 1.8 开始,.success()、.error() 和 .complete() 被弃用,取而代之的是 .done()、.fail() 和 .always()。

注意:请记住,上面的代码片段必须在 DOM 准备好之后完成,因此您应该将其放在 $(document).ready() 处理程序中(或使用 $() 简写)。

提示:您可以像这样链接回调处理程序: $.ajax().done().fail().always();

PHP(即 form.php):

// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$bar = isset($_POST['bar']) ? $_POST['bar'] : null;

注意:请务必清理发布的数据,以防止注入和其他恶意代码。

您也可以在上面的 JavaScript 代码中使用简写 .post 代替:.ajax

$.post('/form.php', serializedData, function(response) {
    // Log the response to the console
    console.log("Response: "+response);
});

注意:上面的 JavaScript 代码适用于 jQuery 1.8 及更高版本,但它应该适用于 jQuery 1.5 之前的版本。

评论

33赞 Philibert Perusse 10/23/2013
一个非常重要的注意事项,因为我花费/浪费/投入了大量时间尝试使用这个例子。您需要将事件绑定在 $(document).ready 块中,或者在执行绑定之前加载 FORM。否则,你会花很多时间试图弄清楚为什么在地狱里没有调用绑定。
5赞 mekwall 10/23/2013
@PhilibertPerusse 与任何事件绑定一样,在尝试绑定到元素之前,或者如果您使用委托绑定,您显然需要元素存在于 DOM 中。
12赞 Philibert Perusse 10/24/2013
是的,我现在明白了。但是我发现许多示例总是放置一个$(document).ready块,以便该示例是独立的。我为未来的用户写了评论,他可能像我一样偶然发现这一点,并最终阅读了评论线程和这个初学者“提示”
7赞 Ben Flynn 4/16/2014
如果要将其应用于自己的代码,请注意,“name”属性对输入至关重要,否则将跳过它们。serialize()
246赞 NullPoiиteя 1/8/2013 #2

要使用 jQuery 发出 Ajax 请求,可以通过以下代码执行此操作。

HTML格式:

<form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>

<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>

JavaScript的:

方法 1

 /* Get from elements values */
 var values = $(this).serialize();

 $.ajax({
        url: "test.php",
        type: "post",
        data: values ,
        success: function (response) {

           // You will get response from your PHP page (what you echo or print)
        },
        error: function(jqXHR, textStatus, errorThrown) {
           console.log(textStatus, errorThrown);
        }
    });

方法 2

/* Attach a submit handler to the form */
$("#foo").submit(function(event) {
    var ajaxRequest;

    /* Stop form from submitting normally */
    event.preventDefault();

    /* Clear result div*/
    $("#result").html('');

    /* Get from elements values */
    var values = $(this).serialize();

    /* Send the data using post and put the results in a div. */
    /* I am not aborting the previous request, because it's an
       asynchronous request, meaning once it's sent it's out
       there. But in case you want to abort it you can do it
       by abort(). jQuery Ajax methods return an XMLHttpRequest
       object, so you can just use abort(). */
       ajaxRequest= $.ajax({
            url: "test.php",
            type: "post",
            data: values
        });

    /*  Request can be aborted by ajaxRequest.abort() */

    ajaxRequest.done(function (response, textStatus, jqXHR){

         // Show successfully for submit message
         $("#result").html('Submitted successfully');
    });

    /* On failure of request this function will be called  */
    ajaxRequest.fail(function (){

        // Show error
        $("#result").html('There is error while submit');
    });

jQuery 1.8 开始,不推荐使用 、 和回调。若要为最终删除代码做好准备,请改用 、 和。.success().error().complete().done().fail().always()

MDN:中止() 。如果请求已发送,此方法将中止请求。

因此,我们已经成功发送了 Ajax 请求,现在是时候将数据抓取到服务器了。

PHP的

当我们在 Ajax 调用 () 中发出 POST 请求时,我们现在可以使用 either 或 获取数据:type: "post"$_REQUEST$_POST

  $bar = $_POST['bar']

您还可以通过以下任一方式查看您在 POST 请求中获得的内容。顺便说一句,请确保已设置。否则,您将收到错误。$_POST

var_dump($_POST);
// Or
print_r($_POST);

并且您正在将值插入到数据库中。在进行查询之前,请确保正确敏感转义所有请求(无论您是 GET 还是 POST)。最好的办法是使用准备好的语句

如果你想将任何数据返回到页面,你可以通过回显该数据来实现,如下所示。

// 1. Without JSON
   echo "Hello, this is one"

// 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below
echo json_encode(array('returned_val' => 'yoho'));

然后你可以得到它,就像:

 ajaxRequest.done(function (response){
    alert(response);
 });

有几种速记方法。您可以使用以下代码。它做同样的工作。

var ajaxRequest= $.post("test.php", values, function(data) {
  alert(data);
})
  .fail(function() {
    alert("error");
  })
  .always(function() {
    alert("finished");
});
29赞 user2610222 9/10/2013 #3

可以使用序列化。下面是一个示例。

$("#submit_btn").click(function(){
    $('.error_status').html();
        if($("form#frm_message_board").valid())
        {
            $.ajax({
                type: "POST",
                url: "<?php echo site_url('message_board/add');?>",
                data: $('#frm_message_board').serialize(),
                success: function(msg) {
                    var msg = $.parseJSON(msg);
                    if(msg.success=='yes')
                    {
                        return true;
                    }
                    else
                    {
                        alert('Server error');
                        return false;
                    }
                }
            });
        }
        return false;
    });
69赞 Mr. Alien 1/18/2014 #4

我想分享一个详细的方法,说明如何使用PHP + Ajax发布,以及失败时抛出的错误。

首先,创建两个文件,例如 和 .form.phpprocess.php

我们将首先创建一个,然后使用该方法提交。其余的将在评论中解释。formjQuery.ajax()


form.php

<form method="post" name="postForm">
    <ul>
        <li>
            <label>Name</label>
            <input type="text" name="name" id="name" placeholder="Bruce Wayne">
            <span class="throw_error"></span>
            <span id="success"></span>
       </li>
   </ul>
   <input type="submit" value="Send" />
</form>


使用 jQuery 客户端验证验证表单,并将数据传递给 。process.php

$(document).ready(function() {
    $('form').submit(function(event) { //Trigger on form submit
        $('#name + .throw_error').empty(); //Clear the messages first
        $('#success').empty();

        //Validate fields if required using jQuery

        var postForm = { //Fetch form data
            'name'     : $('input[name=name]').val() //Store name fields value
        };

        $.ajax({ //Process the form using $.ajax()
            type      : 'POST', //Method type
            url       : 'process.php', //Your form processing file URL
            data      : postForm, //Forms name
            dataType  : 'json',
            success   : function(data) {
                            if (!data.success) { //If fails
                                if (data.errors.name) { //Returned if any error from process.php
                                    $('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
                                }
                            }
                            else {
                                    $('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message
                                }
                            }
        });
        event.preventDefault(); //Prevent the default submit
    });
});

现在我们将看一下进程.php

$errors = array(); //To store errors
$form_data = array(); //Pass back the data to `form.php`

/* Validate the form on the server side */
if (empty($_POST['name'])) { //Name cannot be empty
    $errors['name'] = 'Name cannot be blank';
}

if (!empty($errors)) { //If errors in validation
    $form_data['success'] = false;
    $form_data['errors']  = $errors;
}
else { //If not, process the form, and return true on success
    $form_data['success'] = true;
    $form_data['posted'] = 'Data Was Posted Successfully';
}

//Return the data back to form.php
echo json_encode($form_data);

项目文件可以从 http://projects.decodingweb.com/simple_ajax_form.zip 下载。

10赞 john 9/10/2014 #5
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<form method="post" id="form_content" action="Javascript:void(0);">
    <button id="desc" name="desc" value="desc" style="display:none;">desc</button>
    <button id="asc" name="asc"  value="asc">asc</button>
    <input type='hidden' id='check' value=''/>
</form>

<div id="demoajax"></div>

<script>
    numbers = '';
    $('#form_content button').click(function(){
        $('#form_content button').toggle();
        numbers = this.id;
        function_two(numbers);
    });

    function function_two(numbers){
        if (numbers === '')
        {
            $('#check').val("asc");
        }
        else
        {
            $('#check').val(numbers);
        }
        //alert(sort_var);

        $.ajax({
            url: 'test.php',
            type: 'POST',
            data: $('#form_content').serialize(),
            success: function(data){
                $('#demoajax').show();
                $('#demoajax').html(data);
                }
        });

        return false;
    }
    $(document).ready(function_two());
</script>

评论

1赞 NullPoiиteя 5/8/2015
你的答案和其他答案有什么区别?
13赞 john 5/13/2015
它是由我发布的,其他人是由其他人发布的。
23赞 David Demetradze 1/7/2015 #6

HTML格式

    <form name="foo" action="form.php" method="POST" id="foo">
        <label for="bar">A bar</label>
        <input id="bar" class="inputs" name="bar" type="text" value="" />
        <input type="submit" value="Send" onclick="submitform(); return false;" />
    </form>

JavaScript的:

   function submitform()
   {
       var inputs = document.getElementsByClassName("inputs");
       var formdata = new FormData();
       for(var i=0; i<inputs.length; i++)
       {
           formdata.append(inputs[i].name, inputs[i].value);
       }
       var xmlhttp;
       if(window.XMLHttpRequest)
       {
           xmlhttp = new XMLHttpRequest;
       }
       else
       {
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
       }
       xmlhttp.onreadystatechange = function()
       {
          if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
          {

          }
       }
       xmlhttp.open("POST", "insert.php");
       xmlhttp.send(formdata);
   }
18赞 Shaiful Islam 2/4/2015 #7

我使用如下所示的方式。它像文件一样提交所有内容。

$(document).on("submit", "form", function(event)
{
    event.preventDefault();

    var url  = $(this).attr("action");
    $.ajax({
        url: url,
        type: 'POST',
        dataType: "JSON",
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data, status)
        {

        },
        error: function (xhr, desc, err)
        {
            console.log("error");
        }
    });
});
5赞 Uchiha Itachi 5/8/2016 #8

我多年来一直使用这个简单的一行代码,没有问题(它需要jQuery):

<script src="http://malsup.github.com/jquery.form.js"></script> 
<script type="text/javascript">
    function ap(x,y) {$("#" + y).load(x);};
    function af(x,y) {$("#" + x ).ajaxSubmit({target: '#' + y});return false;};
</script>

这里 ap() 表示 Ajax 页面,af() 表示 Ajax 表单。在表单中,只需调用 af() 函数即可将表单发布到 URL,并将响应加载到所需的 HTML 元素上。

<form id="form_id">
    ...
    <input type="button" onclick="af('form_id','load_response_id')"/>
</form>
<div id="load_response_id">this is where response will be loaded</div>

评论

0赞 johny why 6/14/2018
我希望你包含服务器文件!不知道如何测试。
6赞 pawan sen 5/18/2016 #9

在提交之前和提交成功之后处理 Ajax 错误和加载程序会显示一个带有示例的警报引导框:

var formData = formData;

$.ajax({
    type: "POST",
    url: url,
    async: false,
    data: formData, // Only input
    processData: false,
    contentType: false,
    xhr: function ()
    {
        $("#load_consulting").show();
        var xhr = new window.XMLHttpRequest();

        // Upload progress
        xhr.upload.addEventListener("progress", function (evt) {
            if (evt.lengthComputable) {
                var percentComplete = (evt.loaded / evt.total) * 100;
                $('#addLoad .progress-bar').css('width', percentComplete + '%');
            }
        }, false);

        // Download progress
        xhr.addEventListener("progress", function (evt) {
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
            }
        }, false);
        return xhr;
    },
    beforeSend: function (xhr) {
        qyuraLoader.startLoader();
    },
    success: function (response, textStatus, jqXHR) {
        qyuraLoader.stopLoader();
        try {
            $("#load_consulting").hide();

            var data = $.parseJSON(response);
            if (data.status == 0)
            {
                if (data.isAlive)
                {
                    $('#addLoad .progress-bar').css('width', '00%');
                    console.log(data.errors);
                    $.each(data.errors, function (index, value) {
                        if (typeof data.custom == 'undefined') {
                            $('#err_' + index).html(value);
                        }
                        else
                        {
                            $('#err_' + index).addClass('error');

                            if (index == 'TopError')
                            {
                                $('#er_' + index).html(value);
                            }
                            else {
                                $('#er_TopError').append('<p>' + value + '</p>');
                            }
                        }
                    });
                    if (data.errors.TopError) {
                        $('#er_TopError').show();
                        $('#er_TopError').html(data.errors.TopError);
                        setTimeout(function () {
                            $('#er_TopError').hide(5000);
                            $('#er_TopError').html('');
                        }, 5000);
                    }
                }
                else
                {
                    $('#headLogin').html(data.loginMod);
                }
            } else {
                //document.getElementById("setData").reset();
                $('#myModal').modal('hide');
                $('#successTop').show();
                $('#successTop').html(data.msg);
                if (data.msg != '' && data.msg != "undefined") {

                    bootbox.alert({closeButton: false, message: data.msg, callback: function () {
                            if (data.url) {
                                window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
                            } else {
                                location.reload(true);
                            }
                        }});
                } else {
                    bootbox.alert({closeButton: false, message: "Success", callback: function () {
                        if (data.url) {
                            window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
                        } else {
                            location.reload(true);
                        }
                    }});
                }

            }
        }
        catch (e) {
            if (e) {
                $('#er_TopError').show();
                $('#er_TopError').html(e);
                setTimeout(function () {
                    $('#er_TopError').hide(5000);
                    $('#er_TopError').html('');
                }, 5000);
            }
        }
    }
});
16赞 Juned Ansari 4/13/2017 #10

如果要使用jQuery Ajax发送数据,则不需要表单标记和提交按钮

例:

<script>
    $(document).ready(function () {
        $("#btnSend").click(function () {
            $.ajax({
                url: 'process.php',
                type: 'POST',
                data: {bar: $("#bar").val()},
                success: function (result) {
                    alert('success');
                }
            });
        });
    });
</script>

<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input id="btnSend" type="button" value="Send" />
3赞 Waseem Bashir 10/23/2017 #11

请检查一下。它是完整的 Ajax 请求代码。

$('#foo').submit(function(event) {
    // Get the form data
    // There are many ways to get this data using jQuery (you
    // can use the class or id also)
    var formData = $('#foo').serialize();
    var url = 'URL of the request';

    // Process the form.
    $.ajax({
        type        : 'POST',   // Define the type of HTTP verb we want to use
        url         : 'url/',   // The URL where we want to POST
        data        : formData, // Our data object
        dataType    : 'json',   // What type of data do we expect back.
        beforeSend : function() {

            // This will run before sending an Ajax request.
            // Do whatever activity you want, like show loaded.
        },
        success:function(response){
            var obj = eval(response);
            if(obj)
            {
                if(obj.error==0){
                    alert('success');
                }
                else{
                    alert('error');
                }
            }
        },
        complete : function() {
            // This will run after sending an Ajax complete
        },
        error:function (xhr, ajaxOptions, thrownError){
            alert('error occured');
            // If any error occurs in request
        }
    });

    // Stop the form from submitting the normal way
    // and refreshing the page
    event.preventDefault();
});
2赞 Supun Praneeth 6/16/2019 #12

这是一篇非常好的文章,其中包含您需要了解的有关jQuery表单提交的所有信息。

文章摘要:

简单的HTML表单提交

HTML格式:

<form action="path/to/server/script" method="post" id="my_form">
    <label>Name</label>
    <input type="text" name="name" />
    <label>Email</label>
    <input type="email" name="email" />
    <label>Website</label>
    <input type="url" name="website" />
    <input type="submit" name="submit" value="Submit Form" />
    <div id="server-results"><!-- For server results --></div>
</form>

JavaScript的:

$("#my_form").submit(function(event){
    event.preventDefault(); // Prevent default action
    var post_url = $(this).attr("action"); // Get the form action URL
    var request_method = $(this).attr("method"); // Get form GET/POST method
    var form_data = $(this).serialize(); // Encode form elements for submission

    $.ajax({
        url : post_url,
        type: request_method,
        data : form_data
    }).done(function(response){ //
        $("#server-results").html(response);
    });
});

HTML Multipart/form-data 表单提交

为了将文件上传到服务器,我们可以使用 XMLHttpRequest2 可用的 FormData 接口,该接口构造了一个 FormData 对象,并且可以使用 jQuery Ajax 轻松发送到服务器。

HTML格式:

<form action="path/to/server/script" method="post" id="my_form">
    <label>Name</label>
    <input type="text" name="name" />
    <label>Email</label>
    <input type="email" name="email" />
    <label>Website</label>
    <input type="url" name="website" />
    <input type="file" name="my_file[]" /> <!-- File Field Added -->
    <input type="submit" name="submit" value="Submit Form" />
    <div id="server-results"><!-- For server results --></div>
</form>

JavaScript的:

$("#my_form").submit(function(event){
    event.preventDefault(); // Prevent default action
    var post_url = $(this).attr("action"); // Get form action URL
    var request_method = $(this).attr("method"); // Get form GET/POST method
    var form_data = new FormData(this); // Creates new FormData object
    $.ajax({
        url : post_url,
        type: request_method,
        data : form_data,
        contentType: false,
        cache: false,
        processData: false
    }).done(function(response){ //
        $("#server-results").html(response);
    });
});

我希望这会有所帮助。

5赞 leonheess 7/31/2019 #13

自从引入 Fetch API 以来,真的没有理由再使用 jQuery Ajax 或 XMLHttpRequests 来做这件事了。要在 vanilla JavaScript 中将表单数据 POST 到 PHP 脚本,您可以执行以下操作:

async function postData() {
  try {
    const res = await fetch('../php/contact.php', {
      method: 'POST',
      body: new FormData(document.getElementById('form'))
    })
    if (!res.ok) throw new Error('Network response was not ok.');
  } catch (err) {
    console.log(err)
  }
}
<form id="form" action="javascript:postData()">
  <input id="name" name="name" placeholder="Name" type="text" required>
  <input type="submit" value="Submit">
</form>

下面是一个非常基本的PHP脚本示例,它获取数据并发送电子邮件:

<?php
    header('Content-type: text/html; charset=utf-8');

    if (isset($_POST['name'])) {
        $name = $_POST['name'];
    }

    $to = "[email protected]";
    $subject = "New name submitted";
    $body = "You received the following name: $name";
    
    mail($to, $subject, $body);
11赞 H.A. 10/28/2019 #14

在 php 文件中输入:

$content_raw = file_get_contents("php://input"); // THIS IS WHAT YOU NEED
$decoded_data = json_decode($content_raw, true); // THIS IS WHAT YOU NEED
$bar = $decoded_data['bar']; // THIS IS WHAT YOU NEED
$time = $decoded_data['time'];
$hash = $decoded_data['hash'];
echo "You have sent a POST request containing the bar variable with the value $bar";

并在您的 JS 文件中发送带有数据对象的 AJAX

var data = { 
    bar : 'bar value',
    time: calculatedTimeStamp,
    hash: calculatedHash,
    uid: userID,
    sid: sessionID,
    iid: itemID
};

$.ajax({
    method: 'POST',
    crossDomain: true,
    dataType: 'json',
    crossOrigin: true,
    async: true,
    contentType: 'application/json',
    data: data,
    headers: {
        'Access-Control-Allow-Methods': '*',
        "Access-Control-Allow-Credentials": true,
        "Access-Control-Allow-Headers" : "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization",
        "Access-Control-Allow-Origin": "*",
        "Control-Allow-Origin": "*",
        "cache-control": "no-cache",
        'Content-Type': 'application/json'
    },
    url: 'https://yoururl.com/somephpfile.php',
    success: function(response){
        console.log("Respond was: ", response);
    },
    error: function (request, status, error) {
        console.log("There was an error: ", request.responseText);
    }
  })

或保持表单提交的原样。仅当您要发送包含计算的附加内容的修改请求,而不仅仅是客户端输入的一些表单数据时,才需要此请求。例如哈希、时间戳、用户 ID、会话 ID 等。

3赞 Kamil Kiełczewski 6/22/2020 #15

纯JS

在纯 JS 中,它会简单得多

foo.onsubmit = e=> {
  e.preventDefault();
  fetch(foo.action,{method:'post', body: new FormData(foo)});
}

foo.onsubmit = e=> {
  e.preventDefault();
  fetch(foo.action,{method:'post', body: new FormData(foo)});
}
<form name="foo" action="form.php" method="POST" id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>

0赞 Bhavin Thummar 2/24/2021 #16

我还有一个想法。

其中提供下载文件的 PHP 文件的 URL。 然后你必须通过ajax触发相同的URL,我检查了第二个请求仅在你的第一个请求完成下载文件后才给出响应。所以你可以得到它的事件。

它通过ajax使用相同的第二个请求工作。

1赞 Vinci 3/25/2021 #17

这是填充标签的代码,使用 和 写在 和selectoptionHTMLajaxXMLHttpRequestAPIPHPPDO

conn.php

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$database = "db_event";
try {
    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

类别.php

<?php
 include 'conn.php';
try {
    $data = json_decode(file_get_contents("php://input"));
    $stmt = $conn->prepare("SELECT *  FROM events ");
    http_response_code(200);
    $stmt->execute();
    
    header('Content-Type: application/json');

    $arr=[];
    while($value=$stmt->fetch(PDO::FETCH_ASSOC)){
        array_push($arr,$value);
    }
    echo json_encode($arr);
   
  } catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
  }

脚本.js

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        data = JSON.parse(this.responseText);

        for (let i in data) {


            $("#cars").append(
                '<option value="' + data[i].category + '">' + data[i].category + '</option>'

            )
        }
    }
};
xhttp.open("GET", "http://127.0.0.1:8000/category.php", true);
xhttp.send();

索引.html


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <title>Document</title>
</head>

<body>
    <label for="cars">Choose a Category:</label>

    <select name="option" id="option">
        
    </select>
    
    <script src="script.js"></script>
</body>

</html>