【问题标题】:Send php response to ajax向ajax发送php响应
【发布时间】:2012-04-24 06:49:13
【问题描述】:

好的,我有一个这样结束的 php 脚本:

if ($success)
{
    $result = array('success' => true);
}
else
{
    $result = array('success' => false, 'message' => 'Something happened');
    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
}
  echo json_encode($result);

还有一些我计划在我的脚本运行时提醒我的 jquery。

    jQuery(document).ready(function() {

    $.ajax({
        url: './contactengine.php',
        type: 'GET',
        dataType: 'JSON',
        success: function(response) {
                        alert("GOOD");
                },
                error: function() {
                        alert("BAD");
                }
    });

});

编辑源

【问题讨论】:

  • 您的return 1 语句是否在函数中调用?
  • 您应该将 1 输出为 JSON。
  • @RPM。您使用两个波浪号 = `code` 编写代码
  • @gdoron 感谢您的提醒。
  • @RPM。你的意思是Thanks for the heads up ... :)

标签: php jquery ajax return


【解决方案1】:
        <?php 
        if ($success){
             $result = array("status" => "1");

             echo json_encode($result);
            }
            else{
              print "<meta http-equiv=\"refresh\" content=\"0;URL=/404.html\">";
            }    
        ?>
        <script>
        jQuery(document).ready(function() {

          $.ajax({
                           type: 'GET',
                           url:  'Thatscriptsomething.php',
                           cache: 'false',
                           dataType: 'json',
                           success: function(response) {
                               if(response.status == "1") {
                                    alert("we having a working script");
                               } else {
                                    alert("Oops, script is a no go");
                               }
                            }
                        });
        });
        </script>

【讨论】:

  • 继续处理这个问题,我被转发到一个页面,上面写着:{"success":true} 当它不应该去那里时,它会转到一个页面 domain.com/script.php。
  • 我尝试运行您的脚本,但它不起作用。如果我做警报(响应)我得到了 {"status":1}...所以我想这就是它不起作用的原因。另外,如果我不删除 dataType: 'json' 脚本什么也不做。
【解决方案2】:

基本示例 - 它适用于我

PHP 响应

$value =  array('msg' => 'true' );
          echo json_encode($value);

AJAX 方法

 $.ajax({  
  type: 'post',  
  url: 'URL',  
  contentType: false,
  processData: false,
  dataType:'JSON',
  data: formData,
      success: function(value) {
                if (value.msg ==  'true') {
                      //your action
                }else{
                      //your action
                }
      }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 2013-09-09
    • 2021-03-10
    • 1970-01-01
    相关资源
    最近更新 更多