duanjian4150
2018-03-23 19:19
浏览 61
已采纳

Javascript在Wordpress index.html中处理PHP导致加载问题,而不是匹配小提琴代码

I have a wordpress site where I have retrieved data from the wordpress database using a php script called within index.php.

I want to handle the data acquired through the php script with a JavaScript/jQuery script that will format the data.

The issue is that the code I am using works in JS Fiddle ( https://jsfiddle.net/ocmLe17o/6/) works; it logs the correct raw variable from the HTML and parses it successfully. However, in Wordpress when I include the .js file running the said code in the functions.php file and call the php script, I get no an undefined output console.logged as the svg_links_parsed variable. ("VM691:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse ()"

I suspect the issue may be with the order in which Wordpress loads scripts, and I've tried enqueueing the script after the php including, but I get the same issue.

TL;DR: It works in Fiddle but not wordpress, how do I guarantee the script fires after the php code is inserted if in Wordpress the header is called first and the script is in the header?

Example HTML:

<!DOCTYPE HTML>
<body>
<input type='hidden' id='cover_links' value='["img\/TTEST_1.svg","img\foo.svg","img\/Bar.svg","img\/Derp.svg"]'>
</body>

Javascript:

var raw_src = jQuery("input").val();

console.log(raw_src); //In Fiddle this logs the input string, in Wordpress it's Undefined!

var svg_links_parsed = JSON.parse(raw_src);

document.write(svg_links_parsed);

图片转代码服务由CSDN问答提供 功能建议

我有一个wordpress网站,我使用index.php中调用的php脚本从wordpress数据库中检索数据。

我想通过一个JavaScript / jQuery脚本处理通过php脚本获取的数据,该脚本将格式化数据。

问题是我使用的代码在JS Fiddle中起作用( https://jsfiddle.net/ocmLe17o/6/ )有效; 它从HTML中记录正确的原始变量并成功解析它。 但是,在Wordpress中,当我在functions.php文件中包含运行所述代码的.js文件并调用php脚本时,我没有得到一个未定义的输出console.logged作为svg_links_parsed变量。 (“VM691:1未捕获的SyntaxError:JSON.parse()中位置0 的JSON中的意外标记u”

我怀疑问题可能与Wordpress加载脚本的顺序有关 我已经尝试在php之后将脚本排入队列,但是我得到同样的问题。

TL; DR:它在Fiddle中工作但不是wordpress,我如何保证脚本 插入php代码后触发,如果在Wordpress中首先调用标题并且脚本在标题中?

示例HTML:

 &lt;!DOCTYPE HTML&gt; 
&lt; body&gt; 
&lt; input type ='hidden'id ='cover_links'value ='[“img \ /TTEST_1.svg”,“img \ foo.svg”,“img \  /Bar.svg”, “IMG \ /Derp.svg”]'&GT; 
&LT; /体&GT; 
   
 
 

使用Javascript: \ n

  var raw_src = jQuery(“input”)。val(); 
 
console.log(raw_src); //在Fiddle中记录输入字符串,在Wordpress中它是Undefined!
 
var  svg_links_parsed = JSON.parse(raw_src); 
 
document.write(svg_links_parsed); 
   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanpa5237 2018-03-23 19:28
    已采纳

    You may want to wait until the page is loaded to be sure the script runs after the input tag is loaded into the dom. Stick your code in a document ready :

    $( document ).ready(function() {
      // do stuff after page is loaded. 
    });
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题