2013-05-22 4 views
0

자바 스크립트에서 데이터 (PHP로 획득) 사용에 관한 질문이 있습니다.자바 스크립트에서 PHP 변수를 같은 문서에 사용하십시오.

파일

$(document).ready(function() { 
// CLICK ON SUBMIT BUTTON 
    $("#submit").click(function(e) { 
    // stop form submission first 
    e.preventDefault(); 

    var btn = $(this); 
    btn.button('loading'); 

    // GET VALUE OF APPID 
    var appid = $("#appid").val(); 

    if (isNaN(appid)) 
    { 
     alert("Only numbers allowed!"); 
    } 

    else 
    { 
     // GET JSON FROM PHP SCRIPT 
     $.ajax({ 
      type: 'GET', 
      url: 'loadjson.php', 
      data: { 
       'appid': appid 
      }, 
      success: function (data) { 
       var object = JSON.parse(data); 
       checkCompletion(object); 
      }, 
      error: errorHandler 
     }); 
    } 

    }); // END OF CLICK FUNCTION 
}); // END OF DOCUMENT READY 

파일 main.js

<div class="container"> 
    <form class="well"> 
     <label>Your appid</label> 
     <input type="text" class="span3" id="appid" placeholder="Type your appid here..."> <br> 
     <button type="submit" id="submit" class="btn btn-primary" data-loading-text="Loading..." >Submit</button> 
    </form> 
    <p id="errors" class="text-error"></p> 

</div> <!-- /container --> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')</script> 
<script src="js/main.js"></script> 

index2.html 당신이 볼 수 있듯이 나는 loadjson에 AJAX 호출합니다 이것은 내가 지금하는 일입니다 .php!

파일 loadjson.php 이제

<?php 
    if(isset($_GET['appid']) && !empty($_GET['appid'])) { 
     $appid = $_GET['appid']; 
    } 
    $json_url ='http://api.tapcrowd.com/api/gateway/call/1.4/getApp?appid=' . $appid; 

    $ch = curl_init($json_url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

    $str = curl_exec($ch); 
    curl_close($ch); 

    $data = json_decode($str); 
    $array = json_encode($data); 

    echo $array; 
?> 

내가 AJAX 호출을 할 필요가 없습니다하지만 어쩌면 내 HTML 파일을 사용 PHP를 할 수있는 가능성이 있다면 나는 질문이 있습니다 내 자바 스크립트?

가능하다면 어떻게 알 수 있습니까?

+0

[참고 : 왜 내 자바 스크립트의 PHP 코드가 작동하지 않습니까?] (http://stackoverflow.com/questions/13840429/reference-why-does-the-php-code-in-my- javascript-not-work) – deceze

답변

1

당신의 HTML 문서 확장 .PHP의 경우, 예 당신은 단순히 모든 json_encode 및 기타 기능은 사용의 전에 $ yourVariable에서 수행된다고 가정

var phpValue = "<?=$yourVariable?>"; 

사용할 수 있습니다.

+0

자바 스크립트에이 오류를 넣으면이 오류가 발생합니다. 잡히지 않은 SyntaxError : 예기치 않은 토큰? 다른 js 파일에서 작업하기 때문에 ... – nielsv

+0

@GGio 짧은 태그에서 분명히 조정할 것입니다. *** php.ini *** 파일의 구성 설정이므로 모든 시스템이 짧은 태그를 실행하도록 설정되지는 않습니다. – War10ck

관련 문제