在android webview中调用ajax函数时出现问题CORS策略错误。 我使用服务器上的文本类型向android发送了以下脚本。
api_ticket.php
$ad_script = "<script>
function ad_click(link, str, id){
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if(this.responseText == '1'){ window.location.href = link;
}else{
alert('Server error');
}
}
};
xmlhttp.open('GET','https://skinexam.com/clients/ad_click_count.php?update='+str+'&id='+id,true);
xmlhttp.setRequestHeader('Access-Control-Allow-origin', '*');
xmlhttp.setRequestHeader('Access-Control-Allow-Methods', 'POST,GET, PUT, OPTIONS, DELETE');
xmlhttp.setRequestHeader('Access-Control-Max-Age', '3600');
xmlhttp.setRequestHeader('Access-Control-Allow-Headers', 'x-requested-with, content-type');
xmlhttp.send();
}
</script>";
然后,我在android中加载webview。
.java file in android
txtDocReply.loadDataWithBaseURL(null, ticketModel.getTreatment(), "text/html", "utf-8", null);
ticketModel.getTreatment()具有以下文本。
webview
"<a onclick="ad_click(link, str, id)">some text</a>
<script>
function ad_click(link, str, id){
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if(this.responseText == '1'){ window.location.href = link;
}else{
alert('Server error');
}
}
};
xmlhttp.open('GET','https://skinexam.com/clients/ad_click_count.php?update='+str+'&id='+id,true);
xmlhttp.setRequestHeader('Access-Control-Allow-origin', '*');
xmlhttp.setRequestHeader('Access-Control-Allow-Methods', 'POST,GET, PUT, OPTIONS, DELETE');
xmlhttp.setRequestHeader('Access-Control-Max-Age', '3600');
xmlhttp.setRequestHeader('Access-Control-Allow-Headers', 'x-requested-with, content-type');
xmlhttp.send();
}
</script>";
当在webview中单击某些文本时,我在android webview中调用onclick函数。 onclick功能运行良好。 但是ajax调用中有错误。
error
I/chromium: [INFO:CONSOLE(0)] "Access to XMLHttpRequest at 'https://skinexam.com/clients/ad_click_count.php?update=1&id=46' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.", source: about:blank (0)
我将从Android Webview调用服务器的ad_click_count.php。因此应该重新定向Webview。 有什么好主意吗? 请帮我。 谢谢