Cross-domain javascript <-> php


Cross-domain javascript <-> php

我花了很多时间使用JS和PHP构建一个简单的API。首先,我为您的网站使用了脚本教程Javascript跨域api的示例/解决方案。该代码在标准浏览器上按预期工作;然而,我被IE7卡住了,这个例子在IE7中不起作用。

有什么智慧的话(除了不使用网络爆炸器7)?

提前感谢,Kate

-

根据epascarello的建议,我最终得到了以下内容(这是一个非常脏的测试版本):

来自schock.net的客户端示例:

<html>
<script>
    function jsonpCallback(data){
        alert(data);
    }
    // Create a new script element
    var script_element = document.createElement('script');
    // Set its source to the JSONP API
    script_element.src = 'http://myserver.com/api.php?callback=jsonpCallback';
    // Stick the script element in the page <head>
    document.getElementsByTagName('head')[0].appendChild(script_element);   
</script>
</html>

服务器端示例来自www.geekality.net:

<?php 
header('content-type: application/json; charset=utf-8');
function is_valid_callback($subject)
{
    $identifier_syntax = '/^[$_'p{L}][$_'p{L}'p{Mn}'p{Mc}'p{Nd}'p{Pc}'x{200C}'x{200D}]*+$/u';
    $reserved_words = array('break', 'do', 'instanceof', 'typeof', 'case',
      'else', 'new', 'var', 'catch', 'finally', 'return', 'void', 'continue', 
      'for', 'switch', 'while', 'debugger', 'function', 'this', 'with', 
      'default', 'if', 'throw', 'delete', 'in', 'try', 'class', 'enum', 
      'extends', 'super', 'const', 'export', 'import', 'implements', 'let', 
      'private', 'public', 'yield', 'interface', 'package', 'protected', 
      'static', 'null', 'true', 'false');
    return preg_match($identifier_syntax, $subject) && !in_array(strtolower($subject), $reserved_words);
}
$data = array(1,2,3,4,5,6,7,8,9);
$json = json_encode($data);
# Verify JSON callback and respond
if (is_valid_callback($_GET['callback'])) 
    exit("{$_GET['callback']}($json)");
# Handle a bad request
header('status: 400 Bad Request', true, 400);
?>

答案是你不能用IE7做你正在做的事情,因为它不支持CORS。如果您想支持该浏览器,则需要使用JSONP。