【发布时间】:2014-07-10 19:43:40
【问题描述】:
我正在开发一项涉及发布到 ajax 的功能。相关的代码应该挑选出某个类,循环遍历其元素,将所需的元素放入数组中并发布该数组。它适用于获取背景图像链接。但是,当应用于以 html 文本区域编写的文本时,相同的概念似乎失败了。即使我使用 .val 方法从 textarea 获取文本并将其推送到相关数组中,然后我将其发布,但没有文本被上传到数据库。这是javascript。
$('#createButton').click(function() {
var getImages = [];
var getText = [];
var count = $('.count').length;
var tcount = $('.tcount').length;
if ( count >= 1 ) {
$('.count').each(function () {
if ($(this).css('background-image')) {
var src = $(this).css('background-image');
var parseSrc = src.replace(/^.*(?=images)|\W+$/g, ''); //parse out the actual link from url( link )
getImages.push(parseSrc);
}//end nested if
});//end each function
}//end count if
if ( tcount >= 1 ) {
$('.tcount').each(function () {
if ($(this).val()) {
var textVal = $(this).val();
getText.push(textVal);
}//end if
});//end each
}//end tcount if
$.post('fileHandler.php', {image: getImages, text: getText});//end post
});//end createButton click
还有 PHP
include('classes/fileclass.php');
$f = new Files ();
$storyID = $f->idHandler();
if ($_POST['image']) {
foreach($_POST['image'] as $imageSrc) {
$f->insertStoryImages($storyID, $imageSrc);
}//end foreach
if ($_POST['text']) {
foreach($_POST['text'] as $textBox) {
$f->insertStoryText($storyID, $textBox);
}//end foreach
}//end text if
}//end image if
实际上从 OOP 脚本执行服务器调用的位(仅对于文本调用,图像工作正常):
public function insertStoryText ($storyID, $textBox) {
$db = new pdo("mysql:host=localhost;dbname=storyboard;charset=utf8", "someuser", "somepass");
$stmt = $db->prepare("INSERT INTO sbData(storyID, textBox) VALUES (:storyID, :textBox)");
$stmt->execute(array(':storyID' => $storyID, ':textbox' => $textBox));
}//end insertShoot
注意:为了清楚起见,.tcount 类挑选出一个 html textarea 对象。
【问题讨论】:
-
首先你必须确定错误在哪里。我建议在 PHP 部分的一开始就写入日志或控制台或 $_POST['text'] 的任何内容。这样你就可以集中在 PHP 或 javascript 部分。
-
如果您查看浏览器的 javascript 控制台(至少对于 Chrome 或 Firefox),您应该会看到执行的 AJAX 调用......数据结构是否符合您的预期?如果是这样,则问题出在服务器端。如果没有,它的客户端。
标签: javascript php jquery ajax