php - 如何通过ajax-POST使用jquery将多个字符串发送到数据库到php文件?

标签 php jquery mysql ajax

给出的是:

<input type='text' name='firstname' id='firstname'>
<input type='text' name='lastname' id='lastname'>
<input type='text' name='username' id='username'>
<input id='pw' name='pw' type='password'>

我尝试使用 ajax-post-request 提交数据,如下所示:

                var myData = "firstname="+ $('#firstname').val() + "&lastname="+ $('#lastname').val() + "&username="+ $('#username').val() + "&pw="+ $('#pw').val();
                $.ajax({
                type: "POST",
                url: "php/register.php",
                dataType:"text",
                data:myData, //Form variables
                success:function(response){
                    $("#responds").append(response);
                }

如何以这种方式正确提交该数据到与数据库对应的php文件?是<form>需要使用按钮提交吗?

最佳答案

正如许多人提到的,这个问题有很多解决方案。从我的角度来看,最简单的是将字段包装在表单中。

  1. 绑定(bind) submit提交表单时触发回调的事件。
  2. Serialize使用 .serialize() 的表单以标准 URL 编码表示法创建所有有效输入字段及其值的文本字符串(因此您不必自己构建此查询字符串)
  3. Post使用 $.post 获取数据并使用成功回调处理响应

下面是一个功能齐全的代码片段。可以看到发送到PostBin here的数据.

// PostBin CORS
$.ajaxSetup({crossDomain:true})

// Submit handler
$('form').on('submit', function(event) {
  event.preventDefault();
  var $form = $(this)
  $.post(
    'http://postb.in/ADC3a3Vm',// replace with php/register.php
    $(this).serialize(),
    function(response){
      $("#response").append(response);
      $form[0].reset()
    }
  );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" name="firstname" placeholder="First Name">
  <input type="text" name="lastname" placeholder="Last Name">
  <input type="text" name="username" placeholder="Username">
  <input type="password" name="pw" placeholder="Password">
  <button type="submit">Submit</button>
 </form>
 
 <div id="response"></div>

关于php - 如何通过ajax-POST使用jquery将多个字符串发送到数据库到php文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53339769/

相关文章:

php - 无法将 Illuminate\Routing\Controller 用作 Controller ,因为该名称已被使用

php - Laravel - 显示名称而不是 id

javascript - 为什么在我的图像中移动时需要单击两次才能转到适当的方向?

mysql - 即使权限正常,Sqoop导入错误: Access denied for user 'root' @'localhost' ,

php - 时间戳列未存储为我想要的时区

php - Mercurial 更新之间的数据库同步

php - 如何根据包含的关联数组对php中的数组进行排序?

jquery - Bootstrap .container 菜单中的全宽居中子菜单

jQuery 圆形 slider ?

php - 我的查询哪里出了问题?