使用jQuery和PHP发送和接收AJAX请求

时间:2012-11-24 20:40:28

标签: php javascript jquery ajax

我正在尝试向页面发送一个AJAX请求来解释一些数据,如果它符合我正在寻找的内容,请发回另一个AJAX请求。现在我可以看到第一个请求正在进行,但我没有回来

//message.php
<head>
<script>
function org_name(str){
    alert(str); //this alert appears, so I know the data is being received by this function
    $.get("common_functions.php", { group_name: str} );
}
</script>
</head>    

然后,在common_functions.php上我有一个类似的请求,但是,我不确定究竟是什么问题。警报框甚至没有出现,所以我很困惑为什么控制台会说请求被发送

//common_functions.php

if(isset($_GET['group_name'])){
  ?>
  <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
  <script type="text/javascript">
  alert('common_functions'); //this does not appear
  $.get("message.php", { name: "test"} );
  </script>
  <?
}

当我在chrome中打开javascript控制台时,我看到请求已发送消息给common_functions,但很明显,common_functions上的请求没有发回一个

//text from javascript console
Request URL:http://localhost/message/common_functions.php?group_name=test
Request Method:GET
Status Code:200 OK

有没有人看到一些明显我做错了或丢失的事情?如果它有所不同,common_functions包含在message.php中,因为我确实使用了该页面中的一些其他函数用于我的php。

4 个答案:

答案 0 :(得分:3)

您必须对数据执行某些操作。现在,您正在进行AJAX调用,并且不对您的数据执行任何操作。

如下所示:

$.ajax({
    url: "common_functions.php",
    data: { group_name: str },
    type: "GET",
    success: function (data) {
        $(data).appendTo("head");
    }
});

答案 1 :(得分:1)

如果要控制执行状态,请使用$ .ajax:

        $.ajax({
            type: "POST",
            url: "common_functions.php",
            data: { name: "test"},
            success: function(r)
            {
                 // user r as output
            },
            error: function(xhr, ajaxOptions, thrownError)
            {
                 // error report
                alert(xhr.responseText);
            }
    });

在这种情况下,您可以查看执行是否成功或是否发生错误。

此外,您可以使用firefox或chrome的firebug插件来检测是否已发送响应。还有一个名为Fidler的优秀工具,它可以让您更好地了解请求/响应状态。

Here是ajax调试的优秀教程。

答案 2 :(得分:0)

$.get会删除<script>个标签。您可以使用另一个不会或使用load()的jQuery AJAX方法$.getScript。如果您需要内容和脚本,您可以通过对内容发出ajax请求来执行这两项操作,并在该ajax的成功回调中,使用$.getScript

调用脚本

load()替换指定选择器中的所有内容

$('#myDiv').load('common_functions.php', { name: "test"})  

将获取php输出的所有内容并替换#myDiv的所有内容,但也会运行脚本

答案 3 :(得分:0)

您可以使用http://phery-php-ajax.net使用自动为您执行此操作的库 在你的情况下,它将是

function messages($data){
  $r = new PheryResponse;
  // return your messages
  return $r->json($messages);
}

function common($data){
  $r = new PheryResponse;
  switch ($data['group_name']){
    case 'messages':
       $r
       ->include_script(array( 
         'jquery' => 'http://code.jquery.com/jquery-1.8.2.js'
       ))
       ->phery_remote('messages'); // load your messages
       break;
  }
  return $r;
}

Phery::instance()->set(array(
  'common' => 'common',
  'messages' => 'messages'
))->process();

在你的页面加载

$(function(){
  phery.remote('common', {'group_name': 'messages'});
});

你不需要做任何其他事情。顺便说一句,如果你在使用$.get()后包含jQuery,它将无法正常工作,显然