dongwen2162 2019-05-22 11:22
浏览 40

如何将php变量/函数添加到javascript函数中[重复]

This question already has an answer here:

I cant seem to add a php function / variable into my javascript. I need it to set options into a dynamic select form I have in javascript.

I tried "" inside the javascript which everyone recommended.

<?php
function options(){
include "connection.php";
$sql="SELECT DISTINCT PartID, PartName FROM parts";
$result = mysqli_query($conn,$sql);
if ($result) {
while ($row=mysqli_fetch_assoc($result)){
    echo "<option value='{$row['PartID']}'>{$row['PartName']}</option>";
}}}

?>



<script>
$(function(){
$('p#add_part').click(function(){
counter_part += 1;
$('#container').append(
'<strong>Part No.'+ counter_part + '</strong><br />');
$('#container').append(
            '<select><option>Select a Part</option>((((((HERE))))) 
 </select>');
  });
  });
  </script>

The whole function does not work in relation to the methods I keep trying. When ever I add a '' inside the script to add a variable inside the option, the whole function stops working. However its possible to add a counter variable. Btw I have some other functions above the script etc that was irrelevant.

</div>
  • 写回答

3条回答 默认 最新

  • douren2831 2019-05-22 12:00
    关注

    You can try storing it in an HTML element in PHP, then you can read it from JavaScript and then delete it from JavaScript. You can also set it at the bottom of the page and set the text color the same as the background color so you can't see it. I don't know much about PHP, but I do for JavaScript and HTML, so, sorry but I can only add the JavaScript and HTML.

    HTML:

    <span style="background-color:white; color:white;" id="phpVariable"></span>
    

    JavaScript:

    var element = document.getElementById("phpVariable"); // Get the element
    var phpString = element.textContent; // Get a string
    var phpInteger = parseInt(element.textContent) // Get an integer
    var phpFloat = parseFloat(element.textContent) // Get a float
    element.parentNode.removeChild(element); // Delete the element
    

    For the PHP, you just have to append the HTML element above to the bottom of the page. If you're background is a different color, then you can just set both the background color and the text color to the background color of the page. Doing this will make the text invisible by just looking at it until the JavaScript picks it up and deletes the element.

    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数