You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在jQuery变量中同时使用单双引号?含PHP短代码存储需求

问题分析与解决方案

Hey there! Let's break down why your original approach might be failing and fix it step by step.

The Core Issue

Your current code wraps the PHP output in single quotes, but the do_shortcode() function will generate HTML markup that likely contains single quotes (think of class names, attributes, or even text inside the generated elements). These unescaped single quotes will break your JavaScript string, causing a syntax error before the browser can even parse it. Escaping double quotes doesn't help here because the conflict is with single quotes, not doubles.

Solution 1: Use json_encode() (Most Reliable)

The easiest and safest way to pass a PHP string to JavaScript is using PHP's json_encode() function. It automatically handles all quote escaping, special characters, and ensures the output is a valid JavaScript string.

Here's how to implement it:

var loadMore = <?php echo json_encode(do_shortcode('[ajax_load_more container_type="div" post_type="ps_resources" posts_per_page="6" pause="true" scroll="false" button_label="Load More"]')); ?>;

Notice we don't wrap the PHP output in quotes—json_encode() will add the necessary double quotes and escape any internal quotes automatically. This method works for any string, no matter how many special characters it contains.

Solution 2: Escape Single Quotes Manually

If you prefer to stick with single quotes for your JavaScript string, you need to escape any single quotes that appear in the do_shortcode() output. You can use PHP's addslashes() function or str_replace() to handle this:

Option A with addslashes():

var loadMore = '<?php echo addslashes(do_shortcode('[ajax_load_more container_type="div" post_type="ps_resources" posts_per_page="6" pause="true" scroll="false" button_label="Load More"]')); ?>';

Option B with str_replace():

var loadMore = '<?php echo str_replace("'", "\\'", do_shortcode('[ajax_load_more container_type="div" post_type="ps_resources" posts_per_page="6" pause="true" scroll="false" button_label="Load More"]')); ?>';

Both methods replace any single quotes (') in the PHP output with escaped single quotes (\'), which won't break your JavaScript string.

Quick Debug Tip

If you're still having issues, open your browser's developer tools (F12) and check the Console tab. It will show you exactly where the syntax error is happening—this is usually a dead giveaway that unescaped quotes are causing the problem.

内容的提问来源于stack exchange,提问作者user715564

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:25:57