<script type="text/javascript">
$(document).ready(function() {
$("#fun").focusout(function() {
// alert("Value: " + $("#fun").val());
$.post("<?php echo base_url() ?>index.php/login/email_exists", {
email: $("#fun").val(),
}, function(data, status) {
if (data == 0) {
document.getElementById("error").innerHTML = "Email already exists, Please select another email";
document.getElementById("ddfun").focus();
// alert("email already exists " + data);
} else {
document.getElementById("error").innerHTML = "";
}
//alert("Data: " + data);
});
});
});
</script>
我在我的应用程序中使用了更多jQuery和Ajax。我总是在view.php文件中编写Ajax(带有php代码)。如果有任何选项在外部js文件中添加Ajax。任何帮助将不胜感激。
答案 0 :(得分:1)
您遇到的问题是您正在将一些PHP代码的输出插入到JS中,而这些代码将无法在.js文件中使用。
要解决此问题,您可以将PHP输出作为属性放在元素本身上,并在外部JS文件中将其读回。试试这个:
<!-- in the head -->
<script src="/jquery.js"></script>
<script src="/my-js-code.js"></script>
<!-- example HTML element, the only relevant part is the 'data-base-url' attribute -->
<div id="fun" data-base-url="<?php echo base_url() ?>"></div>
// in my-js-code.js
$(document).ready(function() {
$("#fun").focusout(function() {
$.post($(this).data('base-url') + "index.php/login/email_exists", {
email: $("#fun").val(),
}, function(data, status) {
if (data == 0) {
$("#error").html("Email already exists, Please select another email");
$("#ddfun").focus();
} else {
$("#error").html('');
}
});
});
});
答案 1 :(得分:0)
在调用外部js
之前,在主布局文件中定义js变量<script type = "text/javascript">
var base_url = '<?php echo base_url() ?>';
</script>
现在在外部js
$(document).ready(function() {
$("#fun").focusout(function() {
// alert("Value: " + $("#fun").val());
$.post(base_url + "index.php/login/email_exists", {
email: $("#fun").val(),
},
function(data, status) {
if (data == 0) {
document.getElementById("error").innerHTML = "Email already exists, Please select another email";
document.getElementById("ddfun").focus();
// alert("email already exists " + data);
} else {
document.getElementById("error").innerHTML = "";
}
//alert("Data: " + data);
});
});
答案 2 :(得分:0)
是的,你可以。
你的view.php
<script type = "text/javascript">
var base_url = '<?php echo base_url() ?>';
</script>
<script src="path/to/external.js"></script>
你的外部.js
$(document).ready(function() {
$("#fun").focusout(function() {
// alert("Value: " + $("#fun").val());
$.post(BASE_URL+"index.php/login/email_exists", {
email: $("#fun").val(),
},
function(data, status) {
if (data == 0) {
document.getElementById("error").innerHTML = "Email already exists, Please select another email";
document.getElementById("ddfun").focus();
// alert("email already exists " + data);
} else {
document.getElementById("error").innerHTML = "";
}
//alert("Data: " + data);
});
});
});