如何使用jQuery Ajax提交表单数据而无需刷新页面并在请求页面上获取数据

时间:2019-02-24 13:16:37

标签: jquery ajax

她是我的密码       HTML

#include <stdio.h>

int A[] = {3,1,4,8,6,17};
int nruns = 0;

#define N sizeof(A) / sizeof(int)

int imin(int idx){
 int im = idx;
 for(int i = idx; i < N; ++i, ++nruns)
  if(A[i] < A[im])im = i;
 return im;
}

int swap(li, ri){
 int t = A[li];
 A[li] = A[ri];
 A[ri] = t;
 return 0;
}

int main()
{
 int im;
 for(int i = 0; i < N; ++i){
  im = imin(i);
  swap(i, im);
 }

 for(int i = 0; i < N; ++i)
  printf("%d ", A[i]);
 printf("\nN = %d\nN*N = %d\nnruns = %d\n", N, N*N, nruns);

 /*
  (n*n + n) / 2 < n*n
  Is above always true ?
 */

 return 0;
}

AJAX

<form id="msg_form">
<input type="text" name="msg_text">
<button type="submit" name="send">Send</button>
</form>

现在我想根据请求获取数据 如何发送表格数据并在页面上接收 Php代码

$(function () {

    $('#msg_form').on('send', function (e) {

      e.preventDefault();
      $.ajax({
        type: 'POST',
        url: 'msg.php',
        data: $('#msg_form').serialize(),
        success: function () {

        }
      });

    });

  });

1 个答案:

答案 0 :(得分:1)

好的,这是一个近似值。我对数据字段所做的更改是正确的方式,用于将数据发送回ajax请求。

jQuery

$(function () {
    $('#msg_form').on('send', function (e) {
      e.preventDefault();
      $.ajax({
        type: 'POST',
        url: 'msg.php',
        data: msg_text: $('input[name="msg_text"]'), /*And if you're posting back anything else from the page, sender_id possibly, define same way*/
        success: function () {
          alert('Posted successfully');
        }
      });
    });
  });

php 也许比实际需要的要优雅一些,但是我不确定您走了多远,而且,再次证明,它正确

if($_SERVER['REQUEST_METHOD'] == "POST"){
    if($_POST['msg_text'] != '' && $_POST['sender_id'] != '' && $_SESSION['u_id'] != ''){
        $db_connection = sql_connect();
        if($db_connection->connect_errno){
            echo "Failed to connect to db";
        } else {
            $msg_text = $_POST['msg_text'];
            $receiver_id = $_POST['sender_id'];
            $sender_id = $_SESSION['u_id'];
            $sql = "INSERT INTO `massges` (`msg_text`,`sender_id`,`receiver_id`) values('$msg_text', '$sender_id', $receiver_id)";
            if($db_connection->query($sql) === true){
                echo "Successfully inserted data";
            } else {
                echo "Data not inserted";
            }
        }
        $db_connection->close();
    }
}
//connects to db, return true/false for connection status
function sql_connect(){
    return new mysqli("localhost", "user", "password", "database", /*PORT*/ 3306);
}

如果您还可以向我提供您遇到的任何错误或卡在哪里,我可能可以提供更多信息。