如何执行从ajax响应返回的javascript函数

如何执行从ajax响应返回的javascript函数,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我有一个函数,我想在ajax发出成功请求时执行它,但在这里它不执行我的jquery部分 $.ajax({ type: "POST", url: "https://www.example.com/create_chat.php", data: dataString, beforeSend: function() { $("#loading_indicator").show();

我有一个函数,我想在ajax发出成功请求时执行它,但在这里它不执行我的jquery部分

$.ajax({  
    type: "POST",  
     url: "https://www.example.com/create_chat.php",  
     data: dataString,
        beforeSend: function() 
            {
                $("#loading_indicator").show();
            },  
        success: function(response)
            {
                $(".example").html(response);

            }
        }); 
下面是来自php文件的响应

<script>start_chat(); alert("testing");</script>
但是什么都不管用

试试这个

  $.ajax({
    type: "POST",
    data: {
      'dataString': dataString
    },
    url: 'https://www.example.com/create_chat.php',
    success: function(data) {
      start_chat();
      alert('Success');
    },
    error: function(data) {
      alert('failed');
    }
  });

您在create_chat中的响应可能会指示将使用哪个功能。比如说

$.ajax({  
    type: "POST",  
     url: "https://www.example.com/create_chat.php",  
     data: {
      dataString: dataString
    },
        beforeSend: function() 
            {
                $("#loading_indicator").show();
            },  
        success: function(response) // response could be 1,2,3,4.. etc
            {
                if(response==1) {
                start_chat();
                }
                if(response==2) {
                stop_chat();
                }
                if(response==3) {
                change_chat_room();
                }
                ...
                $(".example").html(response);

            }
        }); 

虽然有一些解决方法,但您永远不应该直接执行Ajax调用的响应

“生成的文档树中的脚本将不会执行, 将不会加载引用的资源,也不会加载关联的XSLT 应用。”


最佳实践是使用数据进行响应,通常是JSON、JSONP或HTML格式。

您想要实现什么?我正在尝试执行从ajax响应中收到的javascript函数,简单地添加start_chat();警报(“测试”);在ajax成功函数中,它不起作用吗?@PeterDarmis,它不起作用executing@SagarSingh要使用的所有函数start_chat等必须位于进行ajax调用的同一页面中。您是否在控制台中收到一个未定义的错误start_chat?关于
start_chat()
$.ajax({  
    type: "POST",  
     url: "https://www.example.com/create_chat.php",  
     data: {
      dataString: dataString
    },
        beforeSend: function() 
            {
                $("#loading_indicator").show();
            },  
        success: function(response) // response could be 1,2,3,4.. etc
            {
                if(response==1) {
                start_chat();
                }
                if(response==2) {
                stop_chat();
                }
                if(response==3) {
                change_chat_room();
                }
                ...
                $(".example").html(response);

            }
        });