php post 透過 ajax 給 https url?

想請問我想讓表單送出後能透過 ajax 傳送到我指定的 https URL api ,然後印出對方api的json回覆訊息?有沒有簡單的範本?

阅读 2.7k
2 个回答
  • 前端ajax请求,因为你请求的是别人的HTTPS api,就涉及到跨域问题了

图片描述

var url = 'https://www.b.com';
var data = {
   user_id : 18
};
function getdata() {
    $.ajax({
        type: 'POST',
        url: url,
        data : data,
        dataType : 'jsonp',
        success: function(res) {
            console.log(res);
        }
    });
}  
  • 通过php中转

图片描述
js

var url = 'https://www.a.com/api/getuser';
var data = {
   user_id : 18
};
function getdata() {
    $.ajax({
        type: 'POST',
        url: url,
        data : data,
        dataType : 'json',
        success: function(res) {
            console.log(res);
        }
    });
}

php

function postdata($url, $data){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    return curl_exec($ch);
}

$url  = 'https://www.b.com/api/getuser';
$data = [
    'user_id' => $_POST['user_id']
];
$res  = postdata($url, $data);
echo json_encode(json_decode($res,true));
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
    function PostData() {
        $.ajax({
            type: "POST",
            url: "https://x/x.php",
            data : "data=" + $("#input_0").val(),
            success: function(msg) {
                alert(msg);
            }
        });
        return false;
    }  
</script>
<form onsubmit="return PostData()">
    <input id="input_0" type="text" value="">
    <input type="submit">
</form>  

https://x/x.php 发送一个 data=[val] 的 post 请求, [val] 是 input_0 标签的内容, 返回的结果在 msg 里.

推荐问题
宣传栏