【问题标题】:Runs php code from JavaScript in impact engine在影响引擎中从 JavaScript 运行 php 代码
【发布时间】:2013-08-04 03:50:21
【问题描述】:

我使用名为Staroids的影响力游戏引擎创建了一个游戏。

我已经创建了一个数据库来存储高分。

我已经完成了之前answer 中所说的操作,并查看了其他一些解决方案,但似乎不起作用!

我正在尝试运行一个包含以下代码的 php 文件:

<?php

    $connect = mysql_connect('localhost', 'root', 'password');
    mysql_select_db('staroids', $connect);

    $sql = 'INSERT INTO staroids (score) VALUES ("'.$_POST['score'].'")';
    $result = mysql_query($sql);

?>

这是我在 JavaScript 文件中运行的代码:

$.post('scripts/register.php', {score: score}, function(){}).error(function(){
    alert('error... ohh no!');
});

当它到达此代码时,在控制台中会出现以下错误:

Uncaught ReferenceError: $ is not defined 

【问题讨论】:

  • 将 "'.$_POST['score'].'" 更改为 '".$_POST['score']."'
  • 不要使用 mysql 扩展。它已经贬值了,还有更好的选择。

标签: php javascript mysql phpmyadmin impactjs


【解决方案1】:

我在上面的 cmets 的帮助下解决了这个问题,并使用了大量的试验和错误,这里是工作代码:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
//make sure you run this otherwise the $post request wont work!

然后在 JavaScript 函数中我想在哪里运行我放置的代码:

$.post('register.php', {score: this.score}, function(){}).error(function(){
    alert('error... ohh no!');
});
//this runs the php file parsing through the score variable

下面是我运行的 PHP 代码,将解析后的变量添加到数据库中的表中:

<?php

    $score = $_POST['score'];
    mysql_connect("localhost", "root", "password");
    mysql_select_db("staroids");
    mysql_query("INSERT INTO scores (score) VALUES ('$score')");

?>

【讨论】:

    【解决方案2】:

    您可能没有正确地将 jQuery 加载到您的页面中。确保头部中有加载 jQuery 的脚本标签,并进行故障排除以确保它实际上正在加载 jQuery。

    【讨论】:

    • 是的 jQuery 正在运行,我认为它一定与游戏引擎 Impact.js 有关,我会在他们的论坛上发帖,不过谢谢!
    • 进入您的控制台并输入$ 并告诉我会发生什么。您可能只需要添加jQuery.noConflict()
    • 对。如果 $ 指的是 jQuery,它会变成这样:function (e,t){return new x.fn.init(e,t,r)};。试着输入jQuery 看看你是否明白。如果是这样,那么 jQuery 正在加载但不使用 $。事实上,为了简单起见,只需输入 $ == jQuery,如果它显示“false”,那就是你的问题。
    • 糟糕,我在 jquery 被注释掉时运行它,当我输入 $ 和输入 jQuery jQuery function ( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); } 时它输出 function ( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }
    • 不知道如何,但它现在似乎可以工作了......好吧,没有更多控制台错误,但它仍然没有发布到数据库中,为@Samuel Reid 的帮助干杯跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 2017-01-16
    • 1970-01-01
    相关资源
    最近更新 更多