2014-10-31 51 views
0

繼續。在Show Malaysia cities based on states chosen將城市名稱從php傳遞給js(第2部分)

  • 市數據JSON ($ cityJsonObject

    Array ([0] => stdClass Object ([cityId] => c1 [cityName] => Kajang [cityStateId] 
    => s2) [1] => stdClass Object ([cityId] => c2 [cityName] => Seputeh 
    [cityStateId] => s1) [2] => stdClass Object ([cityId] => c3 [cityName] => Shah 
    Alam [cityStateId] => s2) [3] => stdClass Object ([cityId] => c4 [cityName] => 
    Klang [cityStateId] => s2) [4] => stdClass Object ([cityId] => c5 [cityName] => 
    Kepong [cityStateId] => s1)) 
    
  • 代碼(的cityName)

    <?php 
        for($i = 0; $i < count($cityJsonObject); $i++) 
        { 
         echo $cityJsonObject[$i]->cityName; 
    
         //PASS VARIABLE TO JS 
        } 
    ?> 
    
    <script type="text/javascript"> 
        //GET VARIABLE FROM PHP AND DISPLAY CITY NAME 
    </script> 
    
  • 從上面的代碼中,我可以得到如下:

    Kajang 
    Seputeh 
    Shah Alam 
    Klang 
    Kepong 
    
  • 我的問題是如何將上述城市名稱傳遞給變量並傳遞給js?我應該怎麼做?

+0

你可以簡單地添加你的php代碼到腳本標記。我的意思是,將你的php代碼寫入腳本標記 – 2014-10-31 06:47:24

回答

1

您可以使用json_encode和輸出,這將很容易被JavaScript

解析字符串試試這個代碼

<?php 
    $array_to_js = array(); 

    for($i = 0; $i < count($cityJsonObject); $i++) 
    { 
     $array_to_js[] = $cityJsonObject[$i]->cityName; 
    } 
?> 

<script type="text/javascript"> 
    //GET VARIABLE FROM PHP AND DISPLAY CITY NAME 
    var js_array = <?php echo json_encode($array_to_js, JSON_HEX_QUOT) ?>; 
</script> 
+0

嗨,UnLoco。謝謝你的幫助。我從你身上學到了很多東西。 – user3905044 2014-10-31 07:34:48

0
<?php 

echo '<script type="text/javascript">'; 

// your php code here maybe you can need json_encode(), I'm not sure I get what you mean. 
echo json_encode($cityJsonObject); 
echo '<script>'; 
?>