简体   繁体   English

PHP和JavaScript:在PHP中获得HTML值

[英]PHP and JavaScript: Getting a HTML value in PHP

I have a span, it looks like this: 我有一个跨度,它看起来像这样:

<span class="price" id="product-price-167">€47.00</span>

The 47.00 is set dynamically using JavaScript. 47.00是使用JavaScript动态设置的。 Now when the user clicks a button, a request to a PHP script is being triggered. 现在,当用户单击按钮时,将触发对PHP脚本的请求。 I need the 47.00 in that script. 我需要该脚本中的47.00。 How could I do that? 我该怎么办? I know JS is front end and PHP is server side, but is there some way? 我知道JS是前端,PHP是服务器端,但是有什么办法吗?

Thanks :) 谢谢 :)

Solution: I am using a hidden field and read that using 解决方案:我正在使用一个隐藏字段,并使用阅读

$price = $_POST["price"];

You can use jquery to retrieve the value of the element: 您可以使用jquery检索元素的值:

var value = $('#product-price-167').text();

I think that should give you the 47.00. 我认为应该给您47.00。

var path = 'path-to-script.php';
var data = 'price='+Number($('#product-price-167').replace(/[^0-9\.]+/g,"")); // to remove redundant [currency] characters
$.post(path, data, function(returnText){
    // do stuff here
});

That should do. 那应该做。

Using JQuery: 使用JQuery:

You can get the price inside the span: 您可以在范围内获得价格:

var price = $('#product-price-167').text();

You can then parse price accordingly to get rid of the Euro sign. 然后,您可以相应地解析价格以摆脱欧元符号。 Without knowing exactly where your button will be placed or how it will work, it's kind of difficult to tell you how to get it to your PHP script. 在不确切知道按钮将放置在何处或如何工作的情况下,很难告诉您如何将其放入PHP脚本。

Note that you shouldn't parse as Float if this is a serious application: Use 请注意,如果这是一个严重的应用程序,则不应将其解析为Float:

var parsedNumber = Number(price.replace(/[^0-9\.]+/g,""));

you can easily use jquery to post that value to php page using ajax 您可以轻松地使用ajax使用jquery将值发布到php页面

<script type="text/javascript">

// i m assuming that 167 in id product-price-167 comes from database in a loop

function buttonClick(pid){
 var price=$("#product-price-"+pid).text();
    $.ajax({
        type : "POST",
        data  : "price="+price,
        url   : "yourphppage.php",
        success :function(data){
            //return something from php page
        }
    });
}
</script>

and your input button 和你的输入按钮

<input type="button" onclick="buttonClick('167')" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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