Best way to Integrate a Javascript result with PHP

后端 未结 3 880
北海茫月
北海茫月 2021-01-14 13:46

Ok.

Basically I am utilizng the Google Maps API - It is Javascript.

My site runs off PHP for the most part.

My intention is to make calls to the Goog

相关标签:
3条回答
  • 2021-01-14 14:03

    To send an answer from JavaScript to PHP requires AJAX:

    If you can use JQuery, which is pretty much a standard, it's really easy. This is verbatim from one of the lessons I wrote for my PHPPro course:

    receiveNumbers.php

    <?php
    if (isset($_GET['sentNums']))
    {
        $sentNumbers = filter_input(INPUT_GET, 'sentNums', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
        // Convert to array.
        $numbers = split(', ', $sentNumbers);
        // Echo out.
        echo json_encode($numbers).
    }
    

    index.php

    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
        <head>
            <title>Graph Sort | PHPExperts.pro</title>
            <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
            <script type="text/javascript" src="js/jquery.json-2.2.min.js"></script>
            <script type="text/javascript">
    var myNumbers = '5, 10, 22, 11';
    var receivedNumbers;
    
    <?php
    // Send data from JavaScript -> PHP.
    if (!isset($_GET['myData']))
    {
    ?>
        jQuery.getJSON('receiveNumbers.php?sentNums=' + myNumbers, function(jsonReceived)
        {
            receivedNumbers = jQuery.parseJSON(jsonReceived);
            alert(receivedNumbers); // Expected [5,10,22,11]
        });
    <?php
    }
    ?>
           </script>
       </head>
    </html>
    
    0 讨论(0)
  • 2021-01-14 14:06

    Yes! I did this just the other day:

    in your PHP file do this (taken straight from my code):

    <?php
    $numbers = array(5, 2, 10, 15);
    /* Model and stuff here */
    ?>
    <html>
        <head>
            <script type="text/javascript">
    // We're going to put all the info we need here, as a JS global variable.
    // If you need even more control, simply fetch it via JQuery from a PHP script that does the following.
    var numbers = <?php echo json_encode($numbers); ?>
    
    alert(numbers);
    // Expected output: [5,2,10,15]
    alert(numbers[2]);
    // Expected output: 10
            </script>
        </head>
    </html>
    

    Cheers!

    0 讨论(0)
  • 2021-01-14 14:07

    I would recommend taking a look at this part of the Google Maps API.

    0 讨论(0)
提交回复
热议问题