dos49618 2014-09-25 11:35
浏览 38
已采纳

如何从一个文件到另一个文件获取php变量可能使用jQuery / javascript?

So, I'm trying to solve a pretty simple problem here but the best part of 4 hours later I still have no idea. I'd just like to take the variable z and convert it to php so I can use the value in an array. At the moment I have managed to convert the value to php in another file now I need to get it back to the original file to use and that's where I've hit a wall. I've included the relevant code below.

orders2.php Takes the javascript value of z and makes it PHP using another file

(function($) {  

    $(document).on('click', '.rowclick',function() {
        var z = 2;
        alert(z);


    var post = $.post('../../wp-content/themes/alma-child/includes/modes.php',{z:z});
    post.done(function(data){

    <?php 
         $rownum = $_GET['z2'];
         echo "nei";
    ?>

    })
      $("#myModal1").modal();       

        });


    })(jQuery);

the modal part in orders2.php

<div id="myModal1" class="modal" tabindex="-1">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-body">
            <div class="account_modal_body">
                <button class="close" type="button" data-dismiss="modal">Close Window</button>
                <div id="missing">
                    <form action="#" id="form" method="post" name="form">
                        <div id="printthis">
                            <h2>Track Mastering Details</h2>
                            <label>Track Name</label>
                            <div class="subsec">
                                <?php echo $waiting[$z2][0] ?>
                            </div>
                            <label>Artist</label>
                            <div class="subsec">
                                <?php echo $waiting[$z2][1] ?>
                            </div>
                            <label>Duration</label>
                            <div class="subsec">
                                <?php echo $waiting[$z2][2] ?>
                            </div>
                            <label>ISRC</label>
                            <div class="subsec">
                                <?php echo $waiting[$z2][3] ?>
                            </div>
                            <label>Mastering Notes</label>
                            <div class="subsec">
                                <?php echo echo $waiting[$z2][4] ?>
                            </div>
                        </div>
                    </form>

                </div>
                <button class="close" id="print" type="button">Print</button>
                </br>
            </div>
        </div>

    </div>
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->

modes.php the other file This code is definitely not correct, I tried to take the jQuery from one of the previous solution but wasn't sure how it worked

<?php $z2=$ _POST['z']; ?>
<div id="uploads">
    <?php echo $z2; ?>
</div>

<script>
    jQuery('#uploads').load('orders2.php?account=<?php echo($z2);?>');
</script>

Notes: I realise this may not be the best way to do this, so any other solutions to convert a javascript variable to php would be appreciated. Also, just to mention I would like it if it was possible for the page not to refresh (hence javascript)

  • 写回答

1条回答 默认 最新

  • duanfeng3879 2014-09-25 12:57
    关注

    As you already know, it won't work the way it is, but let me try to explain why. There are conceptual issues here that will keep getting in your way until you understand them.

    Mixing PHP with JavaScript

    The biggest thing you need to understand is how to mix JavaScript and PHP. This is huge. You can put JavaScript and PHP in the same file, but not in the way you think. Let me show you.

    Here's a simple PHP file that uses jQuery. It contains both JavaScript and PHP.

    (function($) {
        $('#test-button').click(function() {
            <?php echo 'This is a test'; ?>
        });
    })(jQuery);
    

    Now, you might think that when you loaded that file in your browser, PHP would echo This is a test when you clicked an HTML element with the ID test-button, right? Not quite!

    What actually happens is that your web server looks at the file and says, "Hmm, I see PHP tags in here. I'd better process those before I send the file out to the web browser." So it goes to work. It echoes This is a test as it's been told, right inside the click callback. And it does this before the file has ever been sent to the browser. So the file you end up with when you load it into your web browser looks like this:

    (function($) {
        $('#test-button').click(function() {
            This is a test
        });
    })(jQuery);
    

    See? No PHP tags! Before the JavaScript has had a chance to even run, the PHP has been executed. The PHP was run by the server beforehand. (And in this case, we'd end up with an error in the browser. This is a test isn't valid JavaScript!)

    How To Share Data Between PHP and jQuery

    So if PHP is run on the server, how can you share data between jQuery and PHP? The answer is using $.post, which you're already kind of doing. You just need to tweak it a bit. Here's an example.

    Say I have the JavaScript below. I want to ask the server for Mary's favorite color. When the server tells me, I then want to show an alert saying what it is. Here's how I could do that in the JavaScript file. Imagine it's in index.php, in a script tag.

    (function($) {
        var name = "Mary";
        $.post("color.php", { person: name })
        .done(function(data) {
            alert(data.name + "'s favorite color is " + data.color + "!");
        });
    })(jQuery);
    

    You'll notice that we also reference a PHP file, color.php. So we'll have to create that too. Here's what the code in color.php might look like:

    <?php
    $people = array(
        'Eric' => 'blue',
        'Freddie' => 'orange',
        'Mary' => 'blue',
        'Pedro' => 'green'
    );
    
    echo json_encode(array(
        'name' => $_POST['person'],
        'color' => $people[$_POST['person']],
    ));
    

    How It Works Behind the Scenes

    So how does all this work? Here's a breakdown of what happens when you visit the page in the example above.

    1. The browser says, "Hey, web server, I need index.php, please."
    2. The server says, "OK, index.php. Ah, here it is! Let me see. Any PHP tags? Nope, so nothing to render before I send it on to you. OK, here you go!"
    3. The browser gets the file and figures out how to make the HTML look onscreen. It runs any JavaScript in it, too.
    4. When the JavaScript runs, the string Mary is posted to color.php in JSON format. That means a request is sent to the server: "I need to send some data to color.php, OK?" The server says, "Sure! I'll pass that data along and execute any code in the PHP file."
    5. So on the server, the PHP file runs. An associative array of names and favorite colors is set up.
    6. On the last line of the PHP file, the server looks up the value in $people with the key $_POST['person'] (the value of person that jQuery sent over).
    7. The server gets the value and says, "I'll encode that back into JSON format so that JavaScript can work with it right out of the box."
    8. Back in the browser, nothing much has been happening. The browser is just twiddling its thumbs waiting for a response from the server.
    9. The response arrives! The done callback runs.
    10. Inside the done callback, the variable data holds the JSON-encoded array that the server sent back. That array had two keys, remember: name and color. Those are now available to us in data.
    11. An alert pops up using the values in data to tell us what Mary's favorite color is.

    Your Example

    Let's look at your code now. On line 8, you post the variable z to modes.php. Then you have a callback that says, "When the data has been sent successfully, do something." By now you can probably guess why it won't work as is. That PHP has already been run before the JavaScript file even makes it to the browser. And when the PHP ran beforehand, $_GET['z2'] wasn't set.

    So instead of putting the PHP inside the callback, put it in modes.php. modes.php can process the data you post to it. You could use something like the following:

    // z is available in $_POST['z']. This is an example of using it to look up a row
    // representing a blog post in your database if you had a Post model class
    $row = Post::findByPrimaryKey($_POST['z']);
    echo json_encode($row->toArray());
    

    Then the code in your first snippet might look like this:

    // ...
    
    var post = $.post('../../wp-content/themes/alma-child/includes/modes.php',{z:z})
    .done(function(data){
        alert(data.title);
    });
    
    // ...
    

    Conclusion

    In brief, post to modes.php from your jQuery. modes.php runs on the server and returns a value. The callback in your jQuery can then work with that value to do whatever you want.

    I hope that makes sense! Feel free to ask me anything about what's going on here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集