我想从javascript调用PHP函数,这反过来发出调用请求,并将数组响应返回给javascript。它似乎正在工作,但这是我的问题。
1)卷曲请求仅在单击按钮时发生,它是在页面加载时执行的。
2)响应返回一个数组,并显示为无效或意外的令牌。如何将curl响应正确返回给javascript,以便可以阅读?
我所有的HTML,JS和PHP都在一个index.php文件中。这就是内容。
<html>
<head>
<style>
</style>
<!-- <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" type="text/javascript"></script> -->
<!-- <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" /> -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>
<body style="padding:15px;">
<div class="row">
<div class="col-md-12">
<!-- This is where you can insert PHP code directly in HTML markup. -->
<?php
//This example demonstrates that you can insert html markup using php.
echo '<h1>This is Header tags inserted from PHP script</h1>';
//This example demonstrates that you can insert JavaScript markup using php.
echo '<script>console.log("This is JavaScript running inside of a PHP script");</script>';
?>
<!-- ^^^^^PHP closing Tag^^^^ -->
<h1>This is regular html</h1>
</div>
<script>
function callPHP(){
var result ="<?php on_callPhp();?>";
alert(result.trim());
return false;
}
</script>
<div class="col-md-12">
<form action="" method="POST">
<button type="button" id="submitBtn" class="btn btn-primary" onclick="callPHP()">Get Data</button>
</form>
</div>
<?php
function on_callPhp(){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_URL => 'http://jsonplaceholder.typicode.com/todos/',
CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
$response = curl_exec($curl);
echo $response;
}
?>
</body>
</html>