简体   繁体   中英

Javascript handling PHP in Wordpress index.html causing loading issues, not matching fiddle code

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);

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. 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM