Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何转换PHP代码,使其能够使用Ajax添加到.JS中?_Javascript_Php_Jquery_Ajax_Iframe - Fatal编程技术网

Javascript 如何转换PHP代码,使其能够使用Ajax添加到.JS中?

Javascript 如何转换PHP代码,使其能够使用Ajax添加到.JS中?,javascript,php,jquery,ajax,iframe,Javascript,Php,Jquery,Ajax,Iframe,我有一个.js文件托管在domain1.com上,但是为了让它正常工作,我需要在开始时添加一个PHP代码。这样做的原因是为了绕过对脚本Safari的一些限制,它要求我创建一个会话。PHP代码通过指向domain2.com的url创建会话。没有浏览器重定向或任何东西,用户停留在domain1.com中。我想在domain1.com中有一个.js文件,所以也许我需要一个AJAX解决方案。这是: <?php session_start(); if (!isset($_SESSION['is

我有一个.js文件托管在domain1.com上,但是为了让它正常工作,我需要在开始时添加一个PHP代码。这样做的原因是为了绕过对脚本Safari的一些限制,它要求我创建一个会话。PHP代码通过指向domain2.com的url创建会话。没有浏览器重定向或任何东西,用户停留在domain1.com中。我想在domain1.com中有一个.js文件,所以也许我需要一个AJAX解决方案。这是:

<?php
session_start();

  if (!isset($_SESSION['isIFrameSessionStarted']))
    {
        $_SESSION['isIFrameSessionStarted'] = 1;
        $redirect = rawurlencode('http://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
        header('Location: domain2.com/start-session.php?redirect=' . $redirect);


        exit;
    }

?>

start session.php文件位于domain2.com上,不需要任何更改,它包含以下内容:

<?php
    session_start(); // create the session cookie
    $redirect = rawurldecode($_GET['redirect']);

    header('Location: ' . $redirect); // redirect back to domain 
    exit;
?>

如果要在Javascript中重定向,则不能使用从AJAX调用的PHP重定向。您可以传递在PHP中创建的URL并将其发送回JavaScript,然后从那里执行重定向。您可以执行以下操作:

PHP:

JavaScript:

$.get('phpfile', function(result) {
    if (!result) return;
    var data = JSON.parse(result);
    window.location.href = decodeURIComponent(data.url);
});

如果您想在Javascript中重定向,就不能使用从AJAX调用的PHP重定向。您可以传递在PHP中创建的URL并将其发送回JavaScript,然后从那里执行重定向。您可以执行以下操作:

PHP:

JavaScript:

$.get('phpfile', function(result) {
    if (!result) return;
    var data = JSON.parse(result);
    window.location.href = decodeURIComponent(data.url);
});

我不知道你到底想实现什么,但假设你想从php到js再回到php,你可以尝试以下方法:

解决方案1:使用XMLHttpRequest

在PHP(domain1.com)中:

不确定你的重定向链接和东西,但是的,这应该是相当多的工作。不久前也做过类似的事情

解决方案2:使用ajax

使用ajax,您可以有一个JS脚本,如下所示。(类型可以是POST或GET,例如您向php文件发送了一些json。如果您正确地向我描述了您希望发送的内容,则可以更改发送的数据。或者也可以是null

在JS中:

function init_() {
            $.ajax({
                type: 'POST',
                url: 'http://domain2.com/start-session.php',
                data: {json: JSON.stringify(selectedEvent)},
                dataType: 'json'
            }).done(function (data) {
                console.log('done');
                console.log(data);
            }).fail(function (data) {
                console.log('fail');
                console.log(data);
            });
        }
在PHP中: 假设您向PHP发送了一个javascript json。您可以在PHP中使用它,如下所示:

<?php

            $status_header = 'HTTP/1.1 ' . 200 . ' ' . 'OK';
            header($status_header);
            header('Content-type: text/javascript');
            $json = json_decode($_POST['json']); //Do whatever you want with the json or data sent
            echo "This is the returned data"; //Echo returned data back to JS or wherever

?>

不知道您想要实现什么,但假设您想从php到js再回到php,您可以尝试以下方法:

解决方案1:使用XMLHttpRequest

在PHP(domain1.com)中:

不确定你的重定向链接和东西,但是的,这应该是相当大的工作。做了类似的一段时间了

解决方案2:使用ajax

使用ajax,您可以有如下JS脚本。(类型可以是POST或GET,例如您向php文件发送了一些json。如果您正确地向我描述了您希望发送的内容,您可以更改发送的数据。或者也可以为null

在JS中:

function init_() {
            $.ajax({
                type: 'POST',
                url: 'http://domain2.com/start-session.php',
                data: {json: JSON.stringify(selectedEvent)},
                dataType: 'json'
            }).done(function (data) {
                console.log('done');
                console.log(data);
            }).fail(function (data) {
                console.log('fail');
                console.log(data);
            });
        }
在PHP中: 假设您向PHP发送了一个javascript json。您可以在PHP中使用它,如下所示:

<?php

            $status_header = 'HTTP/1.1 ' . 200 . ' ' . 'OK';
            header($status_header);
            header('Content-type: text/javascript');
            $json = json_decode($_POST['json']); //Do whatever you want with the json or data sent
            echo "This is the returned data"; //Echo returned data back to JS or wherever

?>

如果要在扩展了
.js
的文件中运行PHP,可以告诉您的apache web服务器。将以下指令添加到.htaccess或直接添加到apache配置中:

AddType application/x-httpd-php .js
完成此操作后,一旦服务器请求文件,服务器将立即运行包含的PHP代码


更新:


如果要使用JavaScript会话,可以使用AJAX解决方案。为此,在服务器上实现一个web服务,该服务应存储会话值。用于实现的编程语言可以是PHP或可由web服务器运行的另一种语言。使用JavaScript请求web服务。

如果要运行PHP在使用
.js
扩展的文件中,您可以通过告知apache web服务器来执行此操作。将以下指令添加到.htaccess或直接添加到apache配置中:

AddType application/x-httpd-php .js
完成此操作后,一旦服务器请求文件,服务器将立即运行包含的PHP代码


更新:


如果您想使用JavaScript会话,可以使用AJAX解决方案。为此,在服务器上实现一个web服务,该服务应存储会话值。用于实现的编程语言可以是PHP或其他可由web服务器运行的语言。使用JavaScript请求web服务。

为什么不使用脚本直接(如果您将此脚本放在文件顶部,它将等待脚本在domain2中完成会话的创建。(我猜您在domain1中有调用domain2的iframe?)


为什么不直接使用脚本(如果您将此脚本放在文件顶部,它将等待脚本在domain2中完成会话的创建。(我猜您在domain1中有调用domain2的iframe?)


使用jquery和jqxhr对象进行此请求,无需将浏览器发送到第二台服务器,您可以从domain1请求将浏览器加载页加载到初始化会话,而您的客户端永远看不到这一点

//include jquery min library and do next code

$(document).ready(function (){     
var jqxhr = $.get( "http://domain2.com/start-session.php", function() {
  alert( "success" ); //some action for success
})
  .done(function() {
    alert( "second success" ); //when all is done (success done)
  })
  .fail(function() {
    alert( "error" ); //some action for error
  })
  .always(function() {
    alert( "finished" ); //some end action for anycase
  });
});
您可以删除.done函数、.fail函数,并始终按照您的意愿运行。 注意:就绪功能是确保domain1页面完全加载,然后运行脚本


参考

使用jquery和jqxhr对象进行此请求,无需将浏览器发送到第二台服务器,您可以从domain1请求将浏览器加载页面发送到初始化会话,而您的客户端永远看不到这一点

//include jquery min library and do next code

$(document).ready(function (){     
var jqxhr = $.get( "http://domain2.com/start-session.php", function() {
  alert( "success" ); //some action for success
})
  .done(function() {
    alert( "second success" ); //when all is done (success done)
  })
  .fail(function() {
    alert( "error" ); //some action for error
  })
  .always(function() {
    alert( "finished" ); //some end action for anycase
  });
});
您可以删除.done函数、.fail函数,并始终按照您的意愿运行。 注意:就绪功能是确保domain1页面完全加载,然后运行脚本


参考

让我结合您在评论中的要求:

我有一个.js文件托管在domain1…我想要一个单独的js文件,但我不能将PHP放入其中…整个目的是domain1没有任何PHP代码或PHP文件…原因是我希望它跨域,并且会话是从domain2创建的

听起来您的问题可能与有关,特别是因为您有
if(!isset($)\u会话['isIFrameSe]
// Location of the domain B session starter
var sessionScriptURL = "http://domainB.com/start-session.php";
var refQSparam = "phpsessionid";

// Check if we have the phpsessionid in the query string
var phpsessionid = getParameterByName(refQSparam);
if(phpsessionid === null) {
    // Not in the query string, so check if we have it in session storage
    var sessionStore = sessionStorage.getItem(refQSparam);
    if(sessionStore === null) {
        // We have no session storage of the PHP session ID either, redirect to get it
        top.location = sessionScriptURL + "?redirect=" + encodeURIComponent(self.location.href);
    } else {
        // phpsessionid was found in session storage. Retrive it
        phpsessionid = sessionStore;
    }
} else {
    // Save the phpsessionid to session storage for browser refresh
    sessionStorage.setItem(refQSparam, phpsessionid);
    // Optional: Redirect again to remove the extra query string data
}

// Helper to get QS values
function getParameterByName(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
<?php
session_start(); // create the session cookie
$redirect = rawurldecode($_GET['redirect']);

// redirect back with the php session ID
// Optional: encode this information
$href = $redirect . '?phpsessionid=' . session_id();
header('Location: ' . $href);
exit;
<script>
document.write('<iframe src="http://domainB.com/embedded-script.php?phpsessionid='+phpsessionid+'"></iframe>');
</script>
<?php
// Use the phpsessionid passed in
$phpsessionid = rawurldecode($_GET['phpsessionid']);

// REF: http://php.net/manual/en/function.session-id.php
function session_valid_id($session_id) {
    return preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $session_id) > 0;
}
// Check that this is potentially a valid session ID
if(session_valid_id($phpsessionid)) {
    // Set the session to the one obtained in session-start.php
    session_id($phpsessionid);
}
session_start(); // Only call this after session_id()!
// Rest of your code