简体   繁体   English

如何将变量值从JavaScript传递给PHP

[英]How can I pass a variable value from JavaScript to PHP

I've tried this and I do not know if it is the right way: 我已经尝试过了,但不知道这是否正确:

HTML Code: HTML代码:

<div class="container-fluid">
 <form class="form-inline">
    <div class="form-group">
        <label>Choose Records Per Page:</label>
            <select class="form-control input-sm num_rec_per_page">
                <option>5</option>
                <option>10</option>
                <option>50</option>
                <option>100</option>
                <option>150</option>
                <option>200</option>
            </select>
        </div>
    </form>
</div>   

JAVASCRIPT Code: JAVASCRIPT代码:

<script>
    $(document).ready(function(){
        $("select.num_rec_per_page").change(function(){
            $(".num_rec_per_page option:selected").val();
            window.location="?num_rec_per_page=" + num_rec_per_page;
        });
    });
</script>

PHP Code PHP代码

$num_rec_per_page=$_GET['num_re_per_page'];

So this code, when the variable changes, a refresh is made to the webpage, but I do not want that, can you help me?? 因此,当变量更改时,此代码会刷新网页,但我不希望这样做,您能帮我吗?

You didn't specify your exact end goal with getting the JS variable to PHP, but I assume it's to get the value of the select so you can change the number of records displayed per page (inferring from variable names). 您没有通过将JS变量转换为PHP来指定确切的最终目标,但我认为这是要获取select的值,因此您可以更改每页显示的记录数(从变量名推断)。

If you want to avoid a page refresh, you could do this via AJAX and pull in additional records to display using JavaScript. 如果要避免页面刷新,可以通过AJAX进行操作,并提取其他记录以使用JavaScript进行显示。 If you assign a new value to window.location , it will refresh the page. 如果将新值分配给window.location ,它将刷新页面。

You would want something like 你会想要像

$(selector).load('/get_results.php?num_rec_per_page=' + num_rec_per_page);

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

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