php - AJAX 意外 token /未终止的字符串文字

标签 php javascript ajax

我正在使用的页面是:http://glenwoodia.com/business-directory

我在使用分页功能时遇到问题。当您单击其中一个数字(顶部的 1 2 3 4 5 6 7)时,它应该动态提取该组业务并将其显示在页面上。但是,在 Google Chrome 中,我收到“意外 token 非法”错误,在 Firefox/IE 中,我收到“未终止的字符串文字”错误。

在我看来,我必须处理 AJAX 的特定 PHP 代码应该处理任何可能导致问题的流氓字符:

    $listings = trim(strip_tags(str_replace("'","\'",stripslashes(bizdir_directory("",@$v["offset"])))));
    $response = "clearMessage();
        document.getElementById('bizdir_directory').innerHTML = '{$listings}';
    ";

有什么想法吗?

最佳答案

使用json_encode()而不是那些丑陋的 str_replaces ——它负责编码任何在 JavaScript 中无效的内容:

<script type="text/javascript">
var a = <?php echo json_encode("single quote ', double quote \", new
lines"); ?>;
</script>

输出:

<script type="text/javascript">
var a = "single quote ', double quote \", new\r\nlines";
</script>

我认为你的代码可以这样写:

$listings = json_encode(trim(bizdir_directory("", $v["offset"])));
// #1: note that json_encode does not trim the input string
$response = "
    clearMessage();
    document.getElementById('bizdir_directory').innerHTML = {$listings};
"; // #2: note that {$listings} is not enclosed inside quotes

关于php - AJAX 意外 token /未终止的字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7872700/

相关文章:

javascript - jQuery 弹出窗口显示旧内容而不是新内容

javascript - 访问加载时 ajax 请求返回的数据

php - $stmt -> execute() 返回 false

php - 在多个域上运行多个商店时配置 Magento + Apache 的正确方法是什么?

javascript - 如何在 MVC.NET 中使用 jQuery 发送多个数组?

javascript - API 调用未捕获 Formdata 图像文件

javascript - 是否可以在不使用 javascript 的情况下将值从 php 传递回 html 表单?

php - 如何在 WordPress 中搜索我的数据库以获取自定义字段的所有选项?

php - 尽管查询在函数之外工作,但 mySQLi 查询生成空值

javascript - 替换最后 7 个字符的字符串?