我只需单击一下按钮,就可以通过ajax方法运行PHP代码。
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
}
});
});
我希望file.php
能够运行js代码,例如:
if ($time < $_SESSION['time']) {
[...]
}
else {
echo '<script>alert("lol");</script>';
}
当按下页面上的按钮.btn_ranking
时,将显示“大声笑”警报。如果可能的话?
答案 0 :(得分:0)
您可以回显对AJAX调用的响应,然后根据响应运行JS。
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time },
success: function (data) {
if(data==1){
//do this
}else if(data==2){
//do that
alert('LOOL');
}
}
});
});
PHP代码:
if ($time < $_SESSION['time']) {
echo '1';
}
else {
echo '2';
}
答案 1 :(得分:0)
您不能说要使用JavaScript的服务器端脚本。
您要做的是处理ajax的返回,并要求您的前端脚本对其发出警报。像这样的东西:
#include <EGL/egl.h>
namespace davinci {
class window {
EGLDisplay m_display;
EGLSurface m_surface;
EGLContext m_context;
int32_t m_width;
int32_t m_height;
public:
window(EGLDisplay display, EGLSurface surface, EGLContext ctx,
int32_t width, int32_t height);
~window();
// Getters
EGLDisplay display() const;
EGLSurface surface() const;
EGLContext context() const;
int32_t width() const;
int32_t height() const;
// Setters
void display(EGLDisplay d);
void surface(EGLSurface s);
void context(EGLContext ctx);
// Methods
void swap_buffers();
};
};
#include "../include/window.h"
using namespace davinci;
window::window(EGLDisplay display, EGLSurface surface, EGLContext ctx,
int32_t width, int32_t height) :
m_display{display}, m_surface{surface}, m_context{ctx}, m_width{width}, m_height{height}
{
}
window::~window() {
}
EGLDisplay window::display() const { return m_display; }
EGLSurface window::surface() const { return m_surface; }
EGLContext window::context() const { return m_context; }
int32_t window::width() const { return m_width; }
int32_t window::height() const { return m_height; }
void window::display(EGLDisplay d) { m_display = d; }
void window::surface(EGLSurface s) { m_surface = s; }
void window::context(EGLContext ctx) { m_context = ctx; }
void window::swap_buffers() { eglSwapBuffers(m_display, m_surface); }
当您使用ajax调用php脚本时,将在php代码的返回中打印所有内容,并将其返回到HTTP响应,因此在Ajax返回函数中将其作为参数。
答案 2 :(得分:0)
好..首先更改您的js代码以处理来自php脚本的答案:
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time }
success: function(data) {
console.log(data);
// check if it is true/false, show up alert
}
});
});
然后更改php脚本(file.php),如下所示:
$response = [];
if ($time < $_SESSION['time']) {
$response['data'] = false;
}
else {
$response['data'] = true;
}
return json_encode($response);
这样的想法是:)当您使用POST方法发送ajax时,从那里获取变量,不是从$ _SESSION 来:)
您可以看到很好的例子here