我有一個PHP函數,可以對一個API進行cURL調用。我希望通過使用JavaScript單擊按鈕觸發此調用。我怎樣才能得到結果顯示在HTML中,而不是在一個警告框?我的代碼如下:我有一個調用PHP函數的JavaScript函數。我怎樣才能得到的結果顯示在HTML中,而不是在一個警告框?
<script>
function echoSkilljar() {
alert("<?php skilljarApiCall(); ?>");
}
</script>
<?php
function skilljarApiCall() {
// Get cURL resource
$curl = curl_init();
// Set some options - passing a username to Skilljar in the URL
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://api.skilljar.com/v1/users/***********/published-courses',
CURLOPT_HEADER => 0,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERNAME => 'sk-live-***********'
));
// Send the Request & save response to $response
$response = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
// Trim response string to remove leading and trailing "[ and ]"
$trimmed = trim($response, '"[');
$newTrimmed = rtrim($trimmed, ']"');
// Convert trimmed string to JSON
$json = json_encode($newTrimmed);
// Convert JSON to usable associative array
$newJson = json_decode($json);
$array = json_decode($newJson, true);
// Make sure it worked... (fingers crossed);
// var_dump($array);
// Yay it worked! Now make sure we can access the elements of the array...
echo $array['course']['id'] . "/ " . $array['course']['title'];
}
?>
<button onclick="echoSkilljar()">Skilljar Stuff</button>
<div id="info"></div>
歡迎來到Stack Overflow,請[參觀](https://stackoverflow.com/tour),確保你閱讀了[我如何提出一個好問題?](https://stackoverflow.com/幫助/如何問),並更新您的問題與更多的信息。 – lordrhodos
你不能從這樣的js調用php函數... lookup AJAX – rtfm
@rtfm實際上,你可以,但它會回顯值,所以返回的HTML基本上是硬編碼的字符串。 – samanime