繁体   English   中英

在没有加载页面的情况下在php和javascript之间传递变量

[英]pass variable between php and javascript without load page

我是javascript的新手。 这个问题是为了提高我对javascript的理解。 如果使用get或post或request函数加载页面,则传递变量可能很容易。 如何在不加载页面的情况下在php和javascript之间传递变量? 假设我有这个代码

<body>
    <input type='hidden' name='textOption' id='mytext' /><br/>
    <?php
        // Get the value from <input type=hidden ....> from javascript to set as other             variable
        // For example but not logic
        // $variableFromJS = document.getElementById('textOption').value;
    ?>
    <select id="optionValue">
        <option value='none'>--Select--</option>
        <option value="first">First</option>
        <option value="second">Second</option>
        <option value="third">Third</option>
    </select>
    <script type="text/javascript">
    var optionValue = document.getElementById('optionValue');

    optionValue.onchange = function() {
        document.getElementById('textOption').value = optionValue.value;
    }
    </script>
</body>

它可以通过javascript中的ajax调用,

<script type="text/javascript">
var optionValue = document.getElementById('optionValue');

optionValue.onchange = function() {
    document.getElementById('textOption').value = optionValue.value;

  var xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
      document.getElementById("textOption").value = xmlhttp.responseText;
     }
  }
    xmlhttp.open("GET","some_page.php",true);
    xmlhttp.send();
}
</script>

true - > async为falsetrue

some_page.php获取此值并相应地执行操作

如果你想在javascript中学习更多ajax,你可以参考javascript ajax w3schools

你的问题不明确,但根据我的理解,你想得到隐藏字段的任何值,它将是选择框的选定值。 我对吗?

你可以这样做,

//in your html
<input type = "text" value = "first" id = "mytext">


var hidden_field = $('#mytext').val();
$('#optionValue option[value="first"]').attr('selected', true);

如果我错过了问题的概念,请忽略这一点

你可以使用jquery ajax内联你的php脚本...

$.ajax({
    url: 'www.example.com/delete_post/<?php echo $post_id; ?>';
}).done(function() {
    //do some html manipulation here if u want...
});

暂无
暂无

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

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