javascript跨域_您网站的Javascript跨域API

news/2024/5/20 12:29:05/文章来源:https://blog.csdn.net/cuke3186/article/details/107841627

javascript跨域

Javascript cross-domain api for your website
Javascript cross-domain api for your website

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);
elseerror_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);
elseerror_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);

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 functioncfunction(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 functioncfunction(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 functioncfunction(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 functioncfunction(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 functioncfunction(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 functioncfunction(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 functioncfunction(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 functioncfunction(json);}});
}

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 servervar param1 = 5;var param2 = 10;do_sum(param1, param2, function(data) {$('#results').append(param1 + ' + ' + param2 + ' = ' + data.result + '<br />');// execute method 2 (sub) by serverparam1 = 25;param2 = 15;do_sub(param1, param2, function(data) {$('#results').append(param1 + ' - ' + param2 + ' = ' + data.result + '<br />');// execute method 3 (mul) by serverparam1 = 8;param2 = 5;do_mul(param1, param2, function(data) {$('#results').append(param1 + ' * ' + param2 + ' = ' + data.result + '<br />');// execute method 4 (sub) by serverparam1 = 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 servervar param1 = 5;var param2 = 10;do_sum(param1, param2, function(data) {$('#results').append(param1 + ' + ' + param2 + ' = ' + data.result + '<br />');// execute method 2 (sub) by serverparam1 = 25;param2 = 15;do_sub(param1, param2, function(data) {$('#results').append(param1 + ' - ' + param2 + ' = ' + data.result + '<br />');// execute method 3 (mul) by serverparam1 = 8;param2 = 5;do_mul(param1, param2, function(data) {$('#results').append(param1 + ' * ' + param2 + ' = ' + data.result + '<br />');// execute method 4 (sub) by serverparam1 = 33;param2 = 11;do_sub(param1, param2, function(data) {$('#results').append(param1 + ' / ' + param2 + ' = ' + data.result + '<br />');});});});});
});
</script>
<div id="results"></div>

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 />');});

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/

javascript跨域

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_903459.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

如何使用Akismet保护任何网站免受垃圾邮件的侵害

Akismet – spam protection. Today we will continue PHP lessons. And today we will talk about spam protection. I think every one have own website, and every one faced with appearing of unwanted content on the site (spam). What is spam? – this is (usually)…

通过phpstudy搭建简单的网站

1.简单一键构建&#xff1a;下载phpstudy&#xff0c;开启Apache2.4.39和MySQL5.7.26 选择软件管理--网站程序&#xff0c;选择自己想搭建的网站类型&#xff0c;点击一键部署&#xff0c;设置账户密码&#xff0c;搭建成功 2.如果中途报错&#xff0c;或者端口组冲突&#x…

linux宝塔新建站点

网上查了各种资料&#xff0c;绕了一大圈。有的说域名解析有问题&#xff0c;有的说端口问题&#xff0c;说的都是什么鬼东西啊。我特此在此记录下我自己找到的方法&#xff08;做个笔记&#xff09;。 首先新建立站点如图&#xff1a; 准备步骤&#xff1a;不管有没有域名你都…

分享一些省心的PPT模板下载网站资源(附5G优质PPT模板)

分享一些省心的PPT模板下载网站资源&#xff08;附5G优质PPT模板&#xff09; 每次需要做PPT时&#xff0c;总是为找省心的模板二发愁&#xff0c;用搜索引擎搜索“免费PPT模板”时&#xff0c;展示出的大量所谓“免费”的网站。心动的点开一个后&#xff0c;最终却是&#xf…

分享一些省心的PPT模板下载网站资源(附5G优质PPT模板)

每次需要做PPT时&#xff0c;总是为找省心的模板二发愁&#xff0c;用搜索引擎搜索“免费PPT模板”时&#xff0c;展示出的大量所谓“免费”的网站。心动的点开一个后&#xff0c;最终却是&#xff1a;开通会员才免费&#xff0c;满满的套路 现在我们急需那些&#xff0c;省去搜…

免费PPT模板网站

1、51PPT模板 网址&#xff1a;51pptmoban.com/ppt/ 界面&#xff1a; 下载过程&#xff1a; &#xff08;1&#xff09;点击想下载的模板 &#xff08;2&#xff09;页面向下拉&#xff0c;找到“下载地址” &#xff08;3&#xff09;点击“本地下载”&#xff0c;即可。 2…

免费简历模板网站

免费简历模板网站 1.个人简历网 https://www.gerenjianli.com/moban/ 2.超级简历 https://www.wondercv.com/jianlimoban/ 3.菜鸟图库 https://www.sucai999.com/search/word/0_242_0.html?vNTYxMjky

win2003升级到2012 64bitR2后网站报500错误

服务器从win2003升级到2012 64bitR2后网站开始报500错误 由于2012和原来的2003有很大的区别&#xff0c;很多地都不是很熟悉&#xff0c;后来通过在网上搜索加上自己琢磨算是解决了。现在把我的解决方式写一下&#xff0c;说不定能对遇到同样错误的产生帮助。 1、查阅出错原因…

网站第一次打开加载缓慢问题

需要先检测是否页面加载内容过大&#xff0c;再次检测是否数据库连接问题。。如果简单的页面第一次打开仍然较慢&#xff0c;需要检测应用程序池。应用程序池闲置超时默认为20分钟&#xff0c;如果20分钟之内无人点击&#xff0c;则应用程序池将终止&#xff0c;以便在下次访问…

DISCUZ报错:您的服务器不支持 CURL,这将会导致应用无法安装。请联系您的服务商或者网站技术人员

问题&#xff1a; 解决办法1&#xff1a; 找到文件四个文件 php_curl.dll, libeay32.dll, ssleay32.dll php5ts.dll 复制到系统的C:\WINDOWS\system32下; 修改php.ini&#xff0c;将curl扩展打开 重启服务&#xff0c;问题还是没解决。 查找原因&#xff0c;原来是php文…

网站微信扫码支付开发文档含代码

微信扫码支付文档 前言&#xff1a;2021年2月左右完成&#xff0c;内容借鉴哔哩哔哩的教学视频&#xff08;忘记up的昵称了&#xff09; 1.官方文档 官网链接&#xff1a;https://pay.weixin.qq.com/wiki/doc/apiv3/open/pay/chapter2_7_0.shtml 官方文档&#xff1a;https…

支付宝沙箱电脑网站支付(最详细VUE前端 / JAVA后台)

支付宝电脑网站支付 准备工作 首先需要在支付宝开放平台登录并点击控制台选择开发工具沙箱 这个时候就可以看到自己的APPID 和自己的沙箱账号 后面使用沙箱工具登录支付测试使用 开发工作 Jar包引入 <dependency><groupId>com.alipay.sdk</groupId><ar…

有兴趣送自己一个免费且高大上的个人网站吗

大家好&#xff0c;我是戴先生 废话不说&#xff0c;直接上效果图 ##效果图 获取完整代码&#xff0c;可公众号内回复&#xff1a;vuepress 链接地址&#xff1a;你好&#xff0c;戴先生 ![在这里插入图片描述](https://img-blog.csdnimg.cn/ffb2e67a2f594e6bb5b9fd7b90298…

电脑网站调用支付宝进行支付-Java后台调用支付宝支付

网站调用支付宝进行支付-Java后台调用支付宝支付 本文讲的是使用沙箱环境(支付宝提供的一种开发专用模式&#xff0c;不要实际支付&#xff0c;可以走通整个流程)。 一、准备工作 1.首先要到 蚂蚁金服开发者中心 注册商家账户&#xff0c;并认证。 2.下载java版的sdk和demo …

五步快捷搭建大数据网站

快捷搭建网站 [TOC](快捷搭建网站) 前言一、云服务器二、XSHELL三、端口设置四、一键安装五、上传index.html 前言 如何在最快的时间内搭建一个网站 一、云服务器 首先默认大家已经购买了云服务器&#xff0c;本人这边是使用阿里云的ECS&#xff0c;1Mbps 带宽&#xff0c;40…

识别网站所用技术及所有者——builtwith与whois模块学习笔记

很早前入手了一本网络爬虫的书籍&#xff0c;叫《用Python写网络爬虫》&#xff0c;作者是 Richard Lawson, 李斌翻译&#xff0c;人民邮电出版社出版的书籍&#xff08;封面如图&#xff09;。 刚才大概翻了下&#xff0c;个人感觉不太适合纯新手&#xff0c;比较适合有一些Py…

网站配置https

cerbot 安装 letsencrypt 为你的网站添加 htpps安装 cerbot 工具申请证书配置 nginx更新证书 为你的网站添加 htpps 为了网站的安全&#xff0c;通常会为网站配置 https 。https 需要申请证书, 可以选择付费&#xff08;阿里云&#xff09;&#xff0c;免费&#xff08;腾讯云…

手把手教你掌握网站建设、APP设计以及Logo和图标生成

一文带你掌握网站建设、APP设计以及Logo和图标生成 网站建设服务器USBwebserver简介USBwebserver使用方法 程序WordPress简介 域名 APP设计APP开发APP原型设计了解MockPlus使用Mockplus进行APP原型设计 LOGO和图标&#xff50;&#xff48;&#xff4f;&#xff54;&#xff4f…

【天赢金创】0 基础怎样开始学习做网站 (Ruby on Rails)?

这是参加Rails Girls之后写的&#xff0c;最开始想发这边&#xff0c;不过感觉这里工程师大概占90%了(剩下10%是HR)&#xff0c;倒没有太多初学者会来看&#xff0c;所以一直没发 实际上&#xff0c;也不是0基础的教程。原标题为Rails in Plain Language&#xff0c;即用浅显的…

如何将写好的网站放到云服务器上

从阿里云购买了云服务器&#xff0c; 选择了java运行环境&#xff08;MYSQL、Tomcat、Nginx、JDK等&#xff09;。点击阿里云右上角的备案&#xff0c;进行备案。备案完成之后&#xff0c;进行域名解析。下载Xshell 6、Xftp 6及使用教程打开Xshell并建立和云服务器的远程连接后…