Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何根据ajax的结果执行不同的js操作?_Php_Javascript_Jquery_Ajax - Fatal编程技术网

Php 如何根据ajax的结果执行不同的js操作?

Php 如何根据ajax的结果执行不同的js操作?,php,javascript,jquery,ajax,Php,Javascript,Jquery,Ajax,我试图做一些ajax的东西,基本上,根据返回文件(php文件)中的结果,我们在javascript中有不同的操作 例如,假设我正在执行以下操作: $.ajax({ type: 'POST', url: '/something.php', data: 'something=something', cache: false, success: function(data) { $('#something').html(data); }

我试图做一些ajax的东西,基本上,根据返回文件(php文件)中的结果,我们在javascript中有不同的操作

例如,假设我正在执行以下操作:

  $.ajax({
    type: 'POST',
    url: '/something.php',
    data: 'something=something',
    cache: false,
    success: function(data) {
      $('#something').html(data);
    }
  });
如果成功,我的某物div将返回某物。然而,在'something.php'中,可能有这样一个if语句:

if($_POST['something'] == 'not_something') {

    // execute something here

} else {

    // do something else

}
问题是,根据结果,我执行的是javascript,而不是php代码。例如,目前我可以通过这样做来实现:

if($_POST['something'] == 'not_something') {

    echo '<script type="text/javascript">thissucks();</script>';

} else {

    echo '<script type="text/javascript">atleastitworks();</script>';

}
if($\u POST['something']=='not\u something'){
回音“Thissacks();”;
}否则{
回显“atleastitworks();”;
}
但我觉得这不太对。有没有更好的方法来完成这类事情


另一个场景可能是某种ajax搜索函数,它根据是否有结果来执行不同的操作。这类事情。如果没有像我上面所做的那样执行一些真正的groovy内联javascript,如何做到这一点呢?

您可以使用PHP的
json\u encode
格式化一个数组,将指令返回给jQuery
$.ajax()
函数。例如:

<?php

if($_POST['something'] == 'not_something') {
    echo json_encode(array('status'=>'thissucks'));
}
祝你好运

更新
忘记了最重要的数据类型属性,使其eval()成为json

太棒了!!我应该在一年前问这个问题。
$.ajax({
    type: 'POST',
    url: '/something.php',
    date: 'something=something',
    cache: false,
    dataType: 'json', //this is important!
    success: function(data) {
      if(data['status']=='thissucks'){
         //do something here
      }
    }
  });