从其他页面传递参数到文档就绪功能

时间:2016-04-20 11:50:49

标签: javascript jquery function parameters call

我将此代码放在一个单独的js文件中,以便在不重新加载页面的情况下将内容加载到页面中:

$(document).ready(function(){

//Catch the form's submit event:
$('#skipreload').submit(function() {
    //Create AJAX call:
    $.ajax({
        //Get form data:
        data: $(this).serialize(),
        //GET or POST method:
        type: 'GET',
        //The file to call:
        url: 'webaddress.php',
        //On success update div with response:
        success: function(response) {
            $('#form_output').html(response);
        }
    });
    return false;
});
});

我在这样的页面中调用该函数:

<html>
<body>
<head>
<script src="js/script.js">
<!-- Want to create variable to pass parameter to document ready function here -->
</script>
</head>
<body>
(...)

现在我想将'webaddress.php'-url作为参数从HTML页面传递给script.js文件及其提交函数,但我无法使其工作。有人知道如何做到这一点吗?

2 个答案:

答案 0 :(得分:2)

正如@Satpal已经提到的,您可以在HTML中创建一个可在外部脚本中访问的全局变量

<html>
<body>
<head>
<script>var myUrl = 'webaddress.php';</script>
<script src="js/script.js"></script>
</head>
<body>
(...)

在script.js中:

url: myUrl,

注意:在这种情况下,您不要忘记在每个使用script.js的HTML文件中提供此值,否则您将获得myUrl的“未定义”。

答案 1 :(得分:-1)

将其保存在div中并加载其值:

<强> EDITED

<div id='url' style='display:none'>webaddress.php</div>

$(document).ready(function(){
    var url = $("#url").text();
    .
    .
    .
}

<input type='hidden' id='url' value='webaddress.php' />

$(document).ready(function(){
    var url = $("#url").val();
    .
    .
    .
}