您的位置:首页 > 运维架构 > 网站架构

您网站的Javascript跨域API

2020-08-04 22:55 127 查看

Javascript cross-domain api for your website Welcome our readers. Today I would like to give a small but very important lesson where we will create our own cross-domain javascript api. I think that many of you have already tried to implement something similar, and maybe you faced with the impossibility of normal operation with the API functions at third-party domains. Basically, you just can not make a normal AJAX requests to a remote server and receive a reply in your javascript function. And all because of security regulations. But today I’ll show you how to solve this problem.

您网站的Javascript跨域api欢迎我们的读者。 今天,我想给大家一个小而非常重要的课程,在那里我们将创建自己的跨域javascript API。 我认为你们中的许多人已经尝试实现类似的功能,也许您可​​能无法使用第三方域的API函数正常运行。 基本上,您只是无法向远程服务器发出普通的AJAX请求,而无法在javascript函数中收到答复。 都是因为安全法规。 但是今天我将向您展示如何解决此问题。

If you are ready – let’s start coding !

如果您准备好了,那就开始编码吧!

步骤1. PHP (Step 1. PHP)

As the first, we have to prepare our server side:

首先,我们必须准备服务器端:

api.php (api.php)

<?php
// set possibility to send response to any domain
header('Access-Control-Allow-Origin: *');
if (version_compare(phpversion(), '5.3.0', '>=')  == 1)
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
error_reporting(E_ALL & ~E_NOTICE);
// accept POST params
$sAction = $_POST['action'];
$iParam1 = (int)$_POST['param1'];
$iParam2 = (int)$_POST['param2'];
// perform calculation
$iResult = 0;
switch ($sAction) {
case 'sum':
$iResult = $iParam1 + $iParam2;
break;
case 'sub':
$iResult = $iParam1 - $iParam2;
break;
case 'mul':
$iResult = $iParam1 * $iParam2;
break;
case 'div':
$iResult = $iParam1 / $iParam2;
break;
}
// prepare results array
$aResult = array(
'result' => $iResult
);
// generate result
header('Content-type: application/json');
echo json_encode($aResult);
<?php
// set possibility to send response to any domain
header('Access-Control-Allow-Origin: *');
if (version_compare(phpversion(), '5.3.0', '>=')  == 1)
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
error_reporting(E_ALL & ~E_NOTICE);
// accept POST params
$sAction = $_POST['action'];
$iParam1 = (int)$_POST['param1'];
$iParam2 = (int)$_POST['param2'];
// perform calculation
$iResult = 0;
switch ($sAction) {
case 'sum':
$iResult = $iParam1 + $iParam2;
break;
case 'sub':
$iResult = $iParam1 - $iParam2;
break;
case 'mul':
$iResult = $iParam1 * $iParam2;
break;
case 'div':
$iResult = $iParam1 / $iParam2;
break;
}
// prepare results array
$aResult = array(
'result' => $iResult
);
// generate result
header('Content-type: application/json');
echo json_encode($aResult);
[/code]

You should pay attention to the first line of using custom header with ‘Access-Control-Allow-Origin’. It allows to send response to any server (mean – any domain). If you want to restrict it to use at the define domain – you can do it here. After – we do the simple actions, depending on $_POST action we perform different actions with received params. As the most easy example – I decided to implement the most simple math actions as summation, subtraction, multiplication and division. In the long run – we return our result in JSON format. Now, it’s time to prepare our server’s JS library:

您应注意将自定义标头与“ Access-Control-Allow-Origin”一起使用的第一行。 它允许将响应发送到任何服务器(平均–任何域)。 如果要限制其在定义域中使用,可以在此处进行操作。 之后–我们执行简单的动作,根据$ _POST动作,我们对收到的参数执行不同的动作。 作为最简单的例子–我决定实现最简单的数学运算,例如求和,减法,乘法和除法。 从长远来看–我们以JSON格式返回结果。 现在,该准备服务器的JS库了:

步骤2. JavaScript (Step 2. JavaScript)

api.js (api.js)

function do_sum(param1, param2, cfunction) {
// send ajax response to server
$.ajax({
type: 'POST',
url: 'https://www.script-tutorials.com/demos/301/api.php',
crossDomain: true,
dataType: 'json',
data: 'action=sum&param1=' + param1 + '&param2=' + param2,
success: function(json) {
// and evoke client's function
cfunction(json);
}
});
}
function do_sub(param1, param2, cfunction) {
// send ajax response to server
$.ajax({
type: 'POST',
url: 'https://www.script-tutorials.com/demos/301/api.php',
crossDomain: true,
dataType: 'json',
data: 'action=sub&param1=' + param1 + '&param2=' + param2,
success: function(json) {
// and evoke client's function
cfunction(json);
}
});
}
function do_mul(param1, param2, cfunction) {
// send ajax response to server
$.ajax({
type: 'POST',
url: 'https://www.script-tutorials.com/demos/301/api.php',
crossDomain: true,
dataType: 'json',
data: 'action=mul&param1=' + param1 + '&param2=' + param2,
success: function(json) {
// and evoke client's function
cfunction(json);
}
});
}
function do_div(param1, param2, cfunction) {
// send ajax response to server
$.ajax({
type: 'POST',
url: 'https://www.script-tutorials.com/demos/301/api.php',
crossDomain: true,
dataType: 'json',
data: 'action=div&param1=' + param1 + '&param2=' + param2,
success: function(json) {
// and evoke client's function
cfunction(json);
}
});
}
function do_sum(param1, param2, cfunction) {
// send ajax response to server
$.ajax({
type: 'POST',
url: 'https://www.script-tutorials.com/demos/301/api.php',
crossDomain: true,
dataType: 'json',
data: 'action=sum&param1=' + param1 + '&param2=' + param2,
success: function(json) {
// and evoke client's function
cfunction(json);
}
});
}
function do_sub(param1, param2, cfunction) {
// send ajax response to server
$.ajax({
type: 'POST',
url: 'https://www.script-tutorials.com/demos/301/api.php',
crossDomain: true,
dataType: 'json',
data: 'action=sub&param1=' + param1 + '&param2=' + param2,
success: function(json) {
// and evoke client's function
cfunction(json);
}
});
}
function do_mul(param1, param2, cfunction) {
// send ajax response to server
$.ajax({
type: 'POST',
url: 'https://www.script-tutorials.com/demos/301/api.php',
crossDomain: true,
dataType: 'json',
data: 'action=mul&param1=' + param1 + '&param2=' + param2,
success: function(json) {
// and evoke client's function
cfunction(json);
}
});
}
function do_div(param1, param2, cfunction) {
// send ajax response to server
$.ajax({
type: 'POST',
url: 'https://www.script-tutorials.com/demos/301/api.php',
crossDomain: true,
dataType: 'json',
data: 'action=div&param1=' + param1 + '&param2=' + param2,
success: function(json) {
// and evoke client's function
cfunction(json);
}
});
}
[/code]

This is some kind of wrapper for our server side. I prepared 4 JavaScript functions for us: do_sum, do_sub, do_mul and do_div. Every function is for every our server’s function. Generally speaking, what we should to make proper requests: firstly, set the necessary URL of server’s api file (in our’s case it is: https://www.script-tutorials.com/demos/301/api.php), secondly, we should set ‘crossDomain’ to true, and finally – we should set dataType to ‘json’ (in case if we want to get json response). And finally, pay attention, that third param of every function is ‘cfunction’. This is any custom client’s function, and we should pass the server response to this function when we have got this response from our server.

这是我们服务器端的某种包装。 我为我们准备了4个JavaScript函数:do_sum,do_sub,do_mul和do_div。 每个功能都适用于我们服务器的每个功能。 一般而言,我们应该提出适当的请求:首先,设置服务器的api文件的必要网址(在我们的示例中是:https://www.script-tutorials.com/demos/301/api.php),其次,我们应该将'crossDomain'设置为true,最后–我们应该将dataType设置为'json'(以防万一,如果我们想获得json响应)。 最后,请注意,每个函数的第三个参数是“函数”。 这是任何自定义客户端的功能,当我们从服务器获得此响应时,应将服务器响应传递给此函数。

步骤3.用法(客户端) (Step 3. Usage (client side))

In order to use our API’s functions we can prepare an example:

为了使用我们的API函数,我们可以准备一个示例:

<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="https://www.script-tutorials.com/demos/301/api.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// execute method 1 (sum) by server
var param1 = 5;
var param2 = 10;
do_sum(param1, param2, function(data) {
$('#results').append(param1 + ' + ' + param2 + ' = ' + data.result + '<br />');
// execute method 2 (sub) by server
param1 = 25;
param2 = 15;
do_sub(param1, param2, function(data) {
$('#results').append(param1 + ' - ' + param2 + ' = ' + data.result + '<br />');
// execute method 3 (mul) by server
param1 = 8;
param2 = 5;
do_mul(param1, param2, function(data) {
$('#results').append(param1 + ' * ' + param2 + ' = ' + data.result + '<br />');
// execute method 4 (sub) by server
param1 = 33;
param2 = 11;
do_sub(param1, param2, function(data) {
$('#results').append(param1 + ' / ' + param2 + ' = ' + data.result + '<br />');
});
});
});
});
});
</script>
<div id="results"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="https://www.script-tutorials.com/demos/301/api.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// execute method 1 (sum) by server
var param1 = 5;
var param2 = 10;
do_sum(param1, param2, function(data) {
$('#results').append(param1 + ' + ' + param2 + ' = ' + data.result + '<br />');
// execute method 2 (sub) by server
param1 = 25;
param2 = 15;
do_sub(param1, param2, function(data) {
$('#results').append(param1 + ' - ' + param2 + ' = ' + data.result + '<br />');
// execute method 3 (mul) by server
param1 = 8;
param2 = 5;
do_mul(param1, param2, function(data) {
$('#results').append(param1 + ' * ' + param2 + ' = ' + data.result + '<br />');
// execute method 4 (sub) by server
param1 = 33;
param2 = 11;
do_sub(param1, param2, function(data) {
$('#results').append(param1 + ' / ' + param2 + ' = ' + data.result + '<br />');
});
});
});
});
});
</script>
<div id="results"></div>
[/code]

In this example we can see how I use javascript functions of our server. Look at the single example again:

在此示例中,我们可以看到我如何使用服务器的javascript函数。 再看一个例子:

var param1 = 5;
var param2 = 10;
do_sum(param1, param2, function(data) {
$('#results').append(param1 + ' * ' + param2 + ' = ' + data.result + '<br />');
});
var param1 = 5;
var param2 = 10;
do_sum(param1, param2, function(data) {
$('#results').append(param1 + ' * ' + param2 + ' = ' + data.result + '<br />');
});
[/code]

We have just passed 3 params in our function: 2 digits and one function. We will receive the server’s response into this function. And, we can display this result somewhere (as example – we append it to #results element). I hope that everything is easy and understandable. Now you can copy our result’s example code into a new html document at your computer, and open it in your browser to see results.

我们刚刚在函数中传递了3个参数:2位数字和1个函数。 我们将收到服务器对该功能的响应。 并且,我们可以在某个地方显示此结果(例如,将其附加到#results元素中)。 我希望一切都简单易懂。 现在,您可以将结果的示例代码复制到计算机上的新html文档中,然后在浏览器中将其打开以查看结果。

[sociallocker]

[社交储物柜]

存档下载

[/sociallocker]

[/ sociallocker]

结论 (Conclusion)

I hope that everything is clean in today’s code. If you have any suggestions about further ideas for articles – you are welcome to share them with us. Good luck in your work!

我希望今天的代码中的所有内容都是干净的。 如果您对文章的进一步建议有任何建议,欢迎与我们分享。 祝您工作顺利!

翻译自: https://www.script-tutorials.com/javascript-cross-domain-api-for-your-website/

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: