2

我正在尝试向页面发送 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

4 回答 4

3

你必须对你的数据做一些事情。现在,您正在进行 AJAX 调用,并且对您的数据不做任何事情。

所以像下面这样的东西会起作用:

$.ajax({
    url: "common_functions.php",
    data: { group_name: str },
    type: "GET",
    success: function (data) {
        $(data).appendTo("head");
    }
});
于 2012-11-24T20:44:56.153 回答
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);
            }
    });

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

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

是一个很好的ajax调试教程。

于 2012-11-24T20:48:39.260 回答
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'});
});

你不必做任何其他事情。顺便说一句,如果你在使用之后包含 jQuery $.get(),它显然不会工作

于 2012-11-25T08:31:57.513 回答
0

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

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

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

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

于 2012-11-24T20:44:33.470 回答