Javascript Can';无法让AJAX调用或会话正常运行
我有一个非常类似的服务,就像这个帖子中的服务: 我本来会问的,但因为我没有50个名声,我不得不问一个新问题 为了更好地理解Ajax,我想重新创建rkmax的文件,看看它们是否有效。所以我将它们保存为5个单独的文件 会话似乎没有存储任何已发布的信息。增加了一个Javascript Can';无法让AJAX调用或会话正常运行,javascript,php,jquery,ajax,session,Javascript,Php,Jquery,Ajax,Session,我有一个非常类似的服务,就像这个帖子中的服务: 我本来会问的,但因为我没有50个名声,我不得不问一个新问题 为了更好地理解Ajax,我想重新创建rkmax的文件,看看它们是否有效。所以我将它们保存为5个单独的文件 会话似乎没有存储任何已发布的信息。增加了一个print\r($\u会话)以跟踪当前在其中的内容。此外,通过电话号码检索帐户信息的.blur事件也不起作用 好几天来我一直在用这个把头撞墙。当通过Apache/XAMPP在本地托管或在实际的web服务器上工作时,它将不起作用。所有5个文件
print\r($\u会话)代码>以跟踪当前在其中的内容。此外,通过电话号码检索帐户信息的.blur
事件也不起作用
好几天来我一直在用这个把头撞墙。当通过Apache/XAMPP在本地托管或在实际的web服务器上工作时,它将不起作用。所有5个文件都位于同一文件夹中,标题与rkmax的文件标题完全相同
我理解每个函数背后的逻辑,似乎在任何地方都找不到问题。我对编码还很陌生,所以它很容易成为一些明显的东西,比如文件结构或者我自己的电脑设置
阅读其他一些有类似问题的StackOverflow线程,但它们似乎都不适用
谢谢你抽出时间
以下是从rkmax代码中复制的所有内容:
index.php
getCustomerInformation.php
scripts.js
我会尝试做一些小规模的事情,看看这是否是你想要做的。您只需要3个页面,即原始表单页面、php页面和js文件:
/ajax/dispatch.php
/*
** @param $phone [string] Gets key from session
*/
function getCustomerByPhone($phone)
{
if(!empty($_SESSION['customers'][$phone])) {
// I am decoding, but if you have the ability to set,
// create an array like below with success and data
$values = json_decode($_SESSION['customers'][$phone]);
die(json_encode(array("success"=>true,"data"=>$values)));
}
}
function makeError()
{
// Send back error
die(json_encode(array("success"=>false,"data"=>false)));
}
/*
** @param $array [string] This will be a query string generated from the
** jQuery serialize, so it's to be turned to array
*/
function updateSession($array)
{
// This should come back as a string, so you will need to parse it
$data = false;
parse_str(htmlspecialchars_decode($array),$data);
// Update the session
$_SESSION['customers'][$data['phone']] = json_encode($data);
die(json_encode(array("success"=>true,"data"=>$data)));
}
if(isset($_POST['phone'])) {
// If already exists, return to ajax the data
getCustomerByPhone($_POST['phone']);
}
elseif(isset($_POST['data'])) {
updateSession($_POST['data']);
}
// If not exists, return false
makeError();
/scripts.js
// I try not to duplicate things as much as possible
// so I would consider making an object to reuse
var AjaxEngine = function($)
{
this.ajax = function(url,data,func,method)
{
method = (typeof method === "undefined")? 'post' : 'get';
$.ajax({
url: url,
data: data,
type: method,
success: function(response) {
func(response);
}
});
};
};
$(document).ready(function(){
// Create instance
var Ajax = new AjaxEngine($);
var dispatcher = '/ajax/dispatch.php';
// On submit of form
$(this).on('submit','#dataForm',function(e) {
// Get the form
var thisForm = $(this);
// Stop form from firing
e.preventDefault();
// Run ajax to dispatch
Ajax.ajax(dispatcher,
// Serialize form
$('#dataForm').serialize(),
// Create an anonymous function to handle return
function(response) {
// Parse
var resp = JSON.parse(response);
// See if data exists
if(typeof resp.data === "undefined") {
console.log(resp.data);
return false;
}
// If there is a hit in session
else if(resp.success == true) {
// Loop through it and fill empty inputs in form
$.each(resp.data, function(k,v){
var input = $("input[name="+k+"]");
if(input.length > 0) {
if(input.val() == '') {
input.val(v);
}
}
});
}
// Run the session update
Ajax.ajax(dispatcher,
// This time send an action
// (just to differentiate from check function)
{
"action":"update",
"data":thisForm.serialize()
},
function(response) {
// Check your console.
console.log(response);
});
});
});
});
从零开始,我几乎不停地研究我的答案,但很快就要开始工作了,以下是我迄今为止得到的结果;目前,我一直致力于成功地将会话数据发送回javascript,并对其进行解码和显示。一旦我有了这项工作,我认为把它们发送到适当的表格以及邮寄将是微不足道的。如果有人能给我一些建议,让我尽快完成最后一部分,我将不胜感激
编辑:使用最终解决方案进行编辑
index2.php
getPhone.php
posthone.php
如果您在文章中至少包含一个Ajax脚本、匹配的php脚本和HTML标记,对这里的每个人来说都会容易得多。当然没问题。我想这就是一切。你有没有收到任何控制台错误?没有,我没有收到任何错误出现。有没有人尝试过这个代码,它对他们有效?我正在构建一个测试。这一个你似乎过于复杂的什么,它试图做(因为我理解它无论如何)。谢谢你的辛勤工作!可悲的是,它似乎对我仍然不起作用。我现在确信这是我这边的问题。已测试此代码,会话仍在增加。但是电话号码上的模糊呼叫不起作用,post to会话也不起作用。我是否需要安装jQuery、AJAX等才能工作?我还上传了我的文件结构的图像,以确保这不是问题所在,在ajax文件夹中我有dispatch.php。()至于我要做的,我需要这个程序做两件主要的事情:1。当您输入电话号码时,将通过AJAX检索用户信息,并用用户信息填充其他字段。2.当你提交一个新用户时,他们的数据会被添加到会话中。我的用户就是这样做的,除非你已经尝试过,但出于某种原因它没有这样做。是的,我通过XAMPP在我的笔记本电脑和台式机上试过rkmax代码和你的代码,并将其上传到我知道可以运行它的服务器上。我每次在“电话号码”字段中输入“1234567”,然后单击或签出,它没有效果。与尝试发布新用户一样,会话的内容保持不变。你知道是什么导致了这个问题吗?Chrome在两台计算机上的扩展,比如Ghostery或ABP?不要害怕提及最基本的基础知识。好吧,这一个更好用!将新帐户添加到会话中效果很好,当您输入电话号码并提交或按enter键时,将填充用户信息。这一个几乎正是我需要的,除了字段应该填充在电话号码字段的onblur中,而不是在提交时。那么问题仍然是为什么它在您的测试仪上有效,而不是以任何其他方式对我有效。另外,在我关闭浏览器并重新打开tester.php之后,我创建的虚拟帐户(22222222)仍然存在。
session_start();
// example: converts $_POST['phone'] into $post_phone if exists
extract($_POST, EXTR_PREFIX_ALL, 'post');
// Validates that all required information was sent
if (isset($post_lname) && isset($post_fname) && isset($post_phone) && isset($post_account)) {
$customer = array(
'fname' => $post_fname,
'lname' => $post_lname,
'account' => $post_account,
'mi' => isset($post_mi) ? $post_mi : '' // optional
);
$_SESSION['customers'][$post_phone] = json_encode($customer);
// returns a valid json format header
header('Content-Type: application/json');
header("HTTP/1.0 204 No Response");
} else {
// returns error
header('Content-Type: application/json');
header("HTTP/1.0 400 Bad Request");
}
session_start();
// example: converts $_GET['phone'] into $get_phone if exists
extract($_GET, EXTR_PREFIX_ALL, 'get');
if (isset($get_phone) && isset($_SESSION['customers'][$get_phone])) {
header('Content-Type: application/json');
echo $_SESSION['customers'][$get_phone];
} else {
header('Content-Type: application/json');
echo '{}';
}
;(function () {
"use strict";
function getCustomerInformation() {
var phone = jQuery(this).val();
if (!phone) {
return;
}
jQuery.ajax({
type: 'get',
url: 'getCustomerInformation.php',
data: {
phone: phone
},
success: function getCustomerInformation_success(data) {
// for each returned value is assigned to the field
for (var i in data) {
if (data.hasOwnProperty(i)) {
$('#' + i).val(data[i]);
}
}
}
});
}
function postCustomerInformation(event) {
event.preventDefault();
var form = jQuery(this);
jQuery.ajax({
type: 'post',
url: 'postCustomerInformation.php',
data: form.serializeArray(),
success: function postCustomerInformation_success() {
alert("OK");
},
error: function postCustomerInformation_error() {
alert("Error");
}
})
}
// set behaviors when document is ready
jQuery(document).ready(function document_ready() {
jQuery('#phone').blur(getCustomerInformation);
jQuery('#dataForm').submit(postCustomerInformation);
});
})();
/*
** @param $phone [string] Gets key from session
*/
function getCustomerByPhone($phone)
{
if(!empty($_SESSION['customers'][$phone])) {
// I am decoding, but if you have the ability to set,
// create an array like below with success and data
$values = json_decode($_SESSION['customers'][$phone]);
die(json_encode(array("success"=>true,"data"=>$values)));
}
}
function makeError()
{
// Send back error
die(json_encode(array("success"=>false,"data"=>false)));
}
/*
** @param $array [string] This will be a query string generated from the
** jQuery serialize, so it's to be turned to array
*/
function updateSession($array)
{
// This should come back as a string, so you will need to parse it
$data = false;
parse_str(htmlspecialchars_decode($array),$data);
// Update the session
$_SESSION['customers'][$data['phone']] = json_encode($data);
die(json_encode(array("success"=>true,"data"=>$data)));
}
if(isset($_POST['phone'])) {
// If already exists, return to ajax the data
getCustomerByPhone($_POST['phone']);
}
elseif(isset($_POST['data'])) {
updateSession($_POST['data']);
}
// If not exists, return false
makeError();
// I try not to duplicate things as much as possible
// so I would consider making an object to reuse
var AjaxEngine = function($)
{
this.ajax = function(url,data,func,method)
{
method = (typeof method === "undefined")? 'post' : 'get';
$.ajax({
url: url,
data: data,
type: method,
success: function(response) {
func(response);
}
});
};
};
$(document).ready(function(){
// Create instance
var Ajax = new AjaxEngine($);
var dispatcher = '/ajax/dispatch.php';
// On submit of form
$(this).on('submit','#dataForm',function(e) {
// Get the form
var thisForm = $(this);
// Stop form from firing
e.preventDefault();
// Run ajax to dispatch
Ajax.ajax(dispatcher,
// Serialize form
$('#dataForm').serialize(),
// Create an anonymous function to handle return
function(response) {
// Parse
var resp = JSON.parse(response);
// See if data exists
if(typeof resp.data === "undefined") {
console.log(resp.data);
return false;
}
// If there is a hit in session
else if(resp.success == true) {
// Loop through it and fill empty inputs in form
$.each(resp.data, function(k,v){
var input = $("input[name="+k+"]");
if(input.length > 0) {
if(input.val() == '') {
input.val(v);
}
}
});
}
// Run the session update
Ajax.ajax(dispatcher,
// This time send an action
// (just to differentiate from check function)
{
"action":"update",
"data":thisForm.serialize()
},
function(response) {
// Check your console.
console.log(response);
});
});
});
});
<?php
session_start();
if (!isset($_SESSION['customers'])) {
$_SESSION['customers'] = array(
'1111111' => '{"phone": "1111111", "fname": "Za", "lname": "Zo", "mi": "Z", "account": "1234"}',
'2222222' => '{"phone": "2222222", "fname": "La", "lname": "Li", "mi": "L", "account": "4321"}',
);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title> Assignment5 </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type = "text/javascript" src = "scripts.js"></script>
</head>
<body>
<form id="myform">
<input placeholder="Phone Number" name="phone" type="text" id="phone" maxlength="7" autofocus>
<input placeholder="First Name" name="fname" type="text" id="fname">
<input placeholder="Last Name" name="lname" type="text" id="lname">
<input placeholder="Middle Initial" name="mi" type="text" id="mi">
<input placeholder="Account Number" name="account" type="text" id="account" maxlength="4">
<input type="submit" value="Submit">
</form>
</body>
</html>
$(document).ready(function(){
$("#phone").blur(function(){
var session;
var currentPhone = $("#phone").val();
$.get("getPhone.php", {phone: currentPhone}, function(data) {
for (var i in data) {
if (data.hasOwnProperty(i)) {
$('#' + i).val(data[i]);
}
}
});
});
$("form").submit(function(){
var form = jQuery(this);
$.post("postPhone.php", form.serializeArray(), function(data) {
alert(data);
});
});
});
<?php
session_start();
$nowPhone = $_GET["phone"];
if (array_key_exists($nowPhone, $_SESSION['customers'])) {
header('Content-Type: application/json');
echo $_SESSION['customers'][$nowPhone];
} else {
header('Content-Type: application/json');
echo '{}';
}
?>
<?php
session_start();
if (isset($_POST["phone"]) && isset($_POST["fname"]) && isset($_POST["lname"]) && isset($_POST["mi"]) && isset($_POST["account"])) {
echo ("Submitted");
$customer = array(
'phone' => $_POST["phone"],
'fname' => $_POST["fname"],
'lname' => $_POST["lname"],
'mi' => $_POST["mi"],
'account' => $_POST["account"],
);
$_SESSION['customers'][$_POST["phone"]] = json_encode($customer);
}
else
echo ("All Information is Required");
?>