简体   繁体   English

jQuery .post()澄清

[英]Jquery .post() clarification

Hey all, I know this question has been asked a million times before but I just can't seem to convert the answers into my personal project. 大家好,我知道这个问题已经问了一百万遍了,但我似乎无法将答案转化为我的个人项目。 I have a selector on my page that needs to send an AJAX query to my database and retrieve the results and print them under the selector. 我的页面上有一个选择器,需要将AJAX查询发送到数据库并检索结果并将其打印在选择器下。 Thank you to anyone who can clarify what needs to be done for this to work. 感谢所有可以阐明需要做什么才能使它起作用的人。

Here is the php file called "view.php" minus the query I make to the database. 这是一个名为“ view.php”的php文件,减去了我对数据库所做的查询。

$depView = $_POST['depView'];

foreach($result as $entry){
echo  '<div>' . $entry['department']. $entry['CRN']. ' ' . $entry['title'] . ' ' . $entry['addDate'] . '</div>';
}

Here is my Javascript thus far: 到目前为止,这是我的Javascript:

function getProps(data){
        $.post("view.php", {depView: data}, html)

        }

Here is my selector: 这是我的选择器:

<select onchange="getProps(value);" name="depView">
        <option value=""></option>
        <option value="CSC">CSC</option>
        <option value="MAT">MAT</option>
        </select></br>

You must use a the callback function to retrieve data after the successfull request. 成功请求后,必须使用回调函数来检索数据。

It could be something like that : 可能是这样的:

$.post('view.php', {depView: data}, function(data) {
  $('.result').html(data);
});

Just edit the part in the "function(data)" to do what you want with the retrieved data. 只需编辑“功能(数据)”中的零件即可对检索到的数据进行所需的处理。

You should replace your $.post code with: 您应该将$.post代码替换$.post

$.post("view.php",{depView:data},
   function(msg) {
     alert("Data Loaded: " + msg);
   },"html")

msg contains the result of executing view.php msg包含执行view.php的结果

You could replace alert("Data Loaded: " + msg); 您可以替换alert("Data Loaded: " + msg); with $('selector').html(msg) . 使用$('selector').html(msg) The last param html is opotional.jQuery indentifies the type of data send by view.php . 最后一个html参数是opotional.jQuery标识view.php发送的数据类型。

HTML: HTML:

<select name="depView" id="depView">
  <option value=""></option>
  <option value="CSC">CSC</option>
  <option value="MAT">MAT</option>
</select><br />
<div id="ajaxResults"></div>

JavaScript: JavaScript:

<script type="text/javascript">

// on DOM load
$(function () {

  $('#depView').change(function () {
    $.post('view.php',
       { depView: $(this).val() },
       function (data) {
         $('#ajaxResults').html(data);
       },
       'html'
       );
  });

});

</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM