MY AJAX 函数
$(document).ready(function(){
$("#sub").click(function()
{
console.log("Ajax out");
var isbn= $('#isbn').val();
$.ajax({
type:"POST",
url:"httprequestget.php",
data : "isbnn="+isbn,
success:function(response)
{
console.log("Ajax - in ( response)");
alert(response);
}
});
});
});
我的httpgetrequest.php
$isbnn='12345';
$result2=myRestapiGET($isbnn);
function myRestapiGET($isbn)
{
$url = 'http://localhost:8080/Scanbook-server/books/'.$isbn;
$options = array(
'http' => array
(
'method' => 'GET'
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return $result;
}
我想将结果作为 json 格式返回,由 php 中的 get 函数检索到 ajax。但是当我尝试在没有函数的情况下只回显一些随机变量时,我确实得到了响应。
我认为这里的问题是您没有将数据作为对象发送,这就是为什么它仅在您尝试使用随机变量时才起作用的原因。请尝试以下操作:
$("#sub").click(function() {
var isbn= $('#isbn').val();
$.ajax({
type: 'POST',
url: 'httprequestget.php',
data: { isbn: isbn },
success: function (response) {
console.log("Ajax - in ( response)");
alert(response);
}
});
}
希望这有帮助!
不确定我是否正确理解。
在 $.ajax
函数中添加 dataType 属性: dataType: "json"
并使用 php json_encode
在脚本中返回响应Scanbook-server/books/
:
echo json_encode(["book" => "foo", "isbn" =>13456, "response" => 'success']);
您需要回显函数的结果以将其发送回客户端:
$isbnn = $_POST['isbnn'];
$result2=myRestapiGET($isbnn);
echo $result2;