简体   繁体   中英

How I can write a php code inside a jQuery function in main.js file

Maybe for someone it's easy to do, but I can not write well this code:

$("<div id='conferm'></div>")
  .appendTo("#contact")
  .html("<span>Your products is Add!<br>check your cart <a href='<?= $config->urls->root ?>cart'>here</a> or keep to shopping</span>")

The problem is the link not work, because the php $config->urls->root doesn't print the URL but just print it like a text.

If I add this code inside my php page works well, but inside a js file not works.

How I can write it for let the link work well?

Thank you!

<?php 
     echo '<script> var rooturl = ' . $config->urls->root . ';</script>' 
?>

And then change this to:

$("<div id='conferm'></div>")
      .appendTo("#contact")
      .html("<span>Your products is Add!<br>check your cart <a href='" +rooturl+ "cart'>here</a> or keep to shopping</span>");

Take into consideration the load order so that your JS file knows your rooturl variable. Your PHP must print the echo code on your html document before you process it on your JS file.

You can not write PHP code in .js files, because they are made for javascript only. But, you could do the following:

Make ajax function in your .js file, that will get you proper value for your href attribute

 var link_href = ""; $.ajax({ data: "", url: "my_php_file.php", type: "GET", success: function(data){ link_href = data; //data is what your .php file echos //in your example you want to make sure your php files echos only href attribute you need for your <a> tag } }); var a = document.getElementById("a_link"); a.setAttribute("href", link_href); 

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