如何从$ .post调用中获取数据?

时间:2022-10-18 07:37:10

I don't want to refresh a page when I am searching through a database eg. on post, so I had help in using a $.post call which works for sending information. There is a .done(function( data ){ line which I haven't used yet.

我在搜索数据库时不想刷新页面,例如。在帖子上,所以我帮助使用了一个用于发送信息的$ .post调用。有一个.done(函数(数据){行我尚未使用过。

I also came across this question which I'm not sure if this ties to my question.

我也遇到过这个问题,我不确定这是否与我的问题有关。

Return $.get data in a function using jQuery

使用jQuery返回函数中的$ .get数据

I'm trying to search through a database, string match, and return the rows with matching strings. But I want to do this without refreshing the page so I would think that I am using the $.post call and using the .done(function( data ){ which is triggered by javascript (a button).

我正在尝试搜索数据库,字符串匹配,并返回具有匹配字符串的行。但我想这样做而不刷新页面,所以我认为我使用$ .post调用并使用.done(函数(数据){由javascript(一个按钮)触发)。

So I have two parts, the page I'm on and a separate PHP page that processes the call when made.

所以我有两个部分,我正在使用的页面和一个单独的PHP页面,用于处理调用。

How do I make the bridge where I can return the data back? Or is there an easier way to do this?

如何建立可以返回数据的桥?或者有更简单的方法吗?

2 个解决方案

#1


2  

The method .done(function(){}) is exactly what You would like to use, but You can also take a look at third argument (callback) of $.post function.

方法.done(function(){})正是您想要使用的方法,但您也可以查看$ .post函数的第三个参数(回调)。

On server side, do all the queries and prepare the stuff in jsoned array like:

在服务器端,执行所有查询并准备jsoned数组中的东西,如:

// set up data to send
$contentArray = [
    'content' => 'Some content',
    'foo' => 'bar',
];

$jsonResults = json_encode($contentArray);
// you can always send header('Content-Type: application/json'); instead of using simple die function.
die($jsonResults);

Then on client side:

然后在客户端:

<div class="content-container"></div>
<script type="text/javascript">
    function someFunc() {
        (...)
        $.post(addr, values, function(res) {
            var response = $.parseJSON(res);

            $('.content-container').html(response.content);
        });
    }
</script>

This should update the content of the .content-container class only. You can send as much as you want, even prepared view to be displayed in the container. This is up to You.

这应该只更新.content-container类的内容。您可以根据需要发送,甚至准备好的视图也可以显示在容器中。这取决于你。

EDIT:

编辑:

Just to be sure, you're calling someFunc() on some button click event, right? If not, do it as follows:

只是为了确定,你在一些按钮点击事件上调用someFunc(),对吧?如果没有,请按以下步骤操作:

<div class="content-container"></div>
<a href="someScript.php" class="callMe" data-content-id="1">Click here</a>
<script type="text/javascript">
    function changePageContent(addr, contentId) {
        $.post(addr, {contentId:contentId}, function(res) {
            var response = $.parseJSON(res);
            $('.content-container').html(response.content);
        });
    }

    $('.callMe').on('click', function() {
        changePageContent($(this).attr('href'), $(this).attr('data-content-id'));

        return false;
    });
</script>

someScript.php:

someScript.php:

<?php
    // you should force your script to allow only XML HTTP request here
    if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        die('AJAX requests only..');
    }

    // always remember to escape somehow your post values before you use them
    $contentId = is_numeric($_POST['contentId']) ? intval($_POST['contentId']) : null;

    if (null == $contentId) (...) // throw exception or return status=false

    // do your mysql query like: "SELECT * FROM content WHERE id=".$contentId;

    // well, it would be better to send headers instead of that
    die(json_encode([
        'status' => true, // this is a good practice to send some info, if everything is fine, if mysql row has been found etc..
        'result' => $result, // mysql row, this is just in case you need other values to display
        'content' => $result['content'], // I assume you have 'content' column in your mysql
    ]));
?>

#2


2  

Take a look at the docs for Ajax, there really is a lot of info there which will help.

看一下Ajax的文档,确实有很多信息可以帮助你。

In short, you could do something like this:

简而言之,你可以这样做:

  function myPost() {
      // Set the data 
      var data = {
        'key'   : 'value',
        'key_2' : 'value_2' 
      };
      // Do the post
      $.post( '/your-url/', data, callBack );
  }

  function callBack( data ) {
      // If the $.post was successful
      success: function( data ) {
          // do stuff
          console.log( data ); // returned from your endpoint
      },
      // If there was an error
      error: function( jqXHR, textStatus ) {
          // do stuff
          console.log( "Request failed: " + textStatus );
      }
  }

  // On click of your element, fire the post request
  $('#element').on('click', function() {
      myPost();
  });

#1


2  

The method .done(function(){}) is exactly what You would like to use, but You can also take a look at third argument (callback) of $.post function.

方法.done(function(){})正是您想要使用的方法,但您也可以查看$ .post函数的第三个参数(回调)。

On server side, do all the queries and prepare the stuff in jsoned array like:

在服务器端,执行所有查询并准备jsoned数组中的东西,如:

// set up data to send
$contentArray = [
    'content' => 'Some content',
    'foo' => 'bar',
];

$jsonResults = json_encode($contentArray);
// you can always send header('Content-Type: application/json'); instead of using simple die function.
die($jsonResults);

Then on client side:

然后在客户端:

<div class="content-container"></div>
<script type="text/javascript">
    function someFunc() {
        (...)
        $.post(addr, values, function(res) {
            var response = $.parseJSON(res);

            $('.content-container').html(response.content);
        });
    }
</script>

This should update the content of the .content-container class only. You can send as much as you want, even prepared view to be displayed in the container. This is up to You.

这应该只更新.content-container类的内容。您可以根据需要发送,甚至准备好的视图也可以显示在容器中。这取决于你。

EDIT:

编辑:

Just to be sure, you're calling someFunc() on some button click event, right? If not, do it as follows:

只是为了确定,你在一些按钮点击事件上调用someFunc(),对吧?如果没有,请按以下步骤操作:

<div class="content-container"></div>
<a href="someScript.php" class="callMe" data-content-id="1">Click here</a>
<script type="text/javascript">
    function changePageContent(addr, contentId) {
        $.post(addr, {contentId:contentId}, function(res) {
            var response = $.parseJSON(res);
            $('.content-container').html(response.content);
        });
    }

    $('.callMe').on('click', function() {
        changePageContent($(this).attr('href'), $(this).attr('data-content-id'));

        return false;
    });
</script>

someScript.php:

someScript.php:

<?php
    // you should force your script to allow only XML HTTP request here
    if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        die('AJAX requests only..');
    }

    // always remember to escape somehow your post values before you use them
    $contentId = is_numeric($_POST['contentId']) ? intval($_POST['contentId']) : null;

    if (null == $contentId) (...) // throw exception or return status=false

    // do your mysql query like: "SELECT * FROM content WHERE id=".$contentId;

    // well, it would be better to send headers instead of that
    die(json_encode([
        'status' => true, // this is a good practice to send some info, if everything is fine, if mysql row has been found etc..
        'result' => $result, // mysql row, this is just in case you need other values to display
        'content' => $result['content'], // I assume you have 'content' column in your mysql
    ]));
?>

#2


2  

Take a look at the docs for Ajax, there really is a lot of info there which will help.

看一下Ajax的文档,确实有很多信息可以帮助你。

In short, you could do something like this:

简而言之,你可以这样做:

  function myPost() {
      // Set the data 
      var data = {
        'key'   : 'value',
        'key_2' : 'value_2' 
      };
      // Do the post
      $.post( '/your-url/', data, callBack );
  }

  function callBack( data ) {
      // If the $.post was successful
      success: function( data ) {
          // do stuff
          console.log( data ); // returned from your endpoint
      },
      // If there was an error
      error: function( jqXHR, textStatus ) {
          // do stuff
          console.log( "Request failed: " + textStatus );
      }
  }

  // On click of your element, fire the post request
  $('#element').on('click', function() {
      myPost();
  });