drwj4061 2013-08-09 17:28
浏览 86
已采纳

额外的空格/缩进前置于从php打印的字符串

I'm working on a REST api that people can download and throw on their server and use with little to no programming knowledge. https://github.com/evanstoddard/REST-Easy.

I'm using ajax for the setup page and php returns a string for ajax to see and decide whether to move on to the next step or tell the user to fix an error. It seemed to be working fine and then all of a sudden it won't go past the first step.

In my javascript I have the return value from php printed in my log. The first step is for the user to enter mysql server information such as the server url, username, and password. If a connection is created 'success' is returned. I appear to be getting ' success'. With a space or indent in there.

I commented out a lot of code I was working on before this error had occurred and the error is still there. I also added an extra indentation to my if block to check the return and the script succeeded so somewhere an extra bit is being added.

I don't really want to post my code here because there is A LOT of it and there are a bunch of moving parts which probably isn't the best way to go.

Here's a quick rundown of how this works:

User input(html form)->ajax->data handling php script->class_database.php(prints success->ajax->html

Applicable code:

Html:

    <form onsubmit="stepTwo('#stepOneForm'); return false;" id="stepOneForm">
        <input type="hidden" name="task" value="1" />
        <input type="text" class="inputText" id="serverURL" name="serverURL" placeholder="MySQL Server:" /><br />
        <input type="text" class="inputText" id="serverUsername" name="serverUsername" placeholder="Username:" /><br />
        <input type="text" class="inputText" id="serverPassword" name="serverPassword" placeholder="Password:" /><br />
        <input type="submit" class="blueButton" value="Connect" />
    </form>

Javascript(AJAX):

function setupForm(form){
    //console.log('Form function called.');
    var formData = $(form).serialize();

    $.ajax({
        type: "POST",
        url: "data/data_setup.php",
        data: formData,

        success: function(result) { 

        console.log(result)

        function showAndTell(hide, show){

            $(show).slideDown(600);
            $(hide).delay(300).slideUp(600);

        }

        function showMessage(message, type, holdMessage){

            var messageContainer = "#messageContainer";
            var messageText = "#messageText";
            var messageImage = "#messageImage";

            var errorImage = "<img src='images/error.png' alt='Error' height='60px' width='60px' />";
            var successImage = "<img src='images/success.png' alt='Error' height='60px' width='60px' />";

            if (type === 'error'){

                $(messageText).empty()
                $(messageImage).empty()
                $(messageText).append(message)
                $(messageImage).append(errorImage)
                $(messageContainer).slideDown(500)
                if (!holdMessage) {
                    $(messageContainer).delay(7000).slideUp(500)
                }


            }

            else if(type === 'success'){

                $(messageText).empty()
                $(messageImage).empty()
                $(messageText).append(message)
                $(messageImage).append(successImage)
                $(messageContainer).slideDown(500)
                if (!holdMessage) {
                    $(messageContainer).delay(7000).slideUp(500)
                }               



            }
        }   


        if(result === 'success'){

            showAndTell('#stepOne', '#stepTwo');
            showMessage('Successfully connected to MySQL database.', 'success');

        }

        else if (result === 'badaccess') {

            showMessage('Unsuccessful.  Please recheck information.', 'error');

        }
        else if (result === 'nserver') {
            showMessage('Please enter a server URL.', 'error');
            $('#serverURL').css('background', '#ffdadb');
        }
        else if (result === 'nserverusername') {
            showMessage('Please enter a server username.', 'error');
            $('#serverUsername').css('background', '#ffdadb');
        }
        else if (result === 'ndatabase') {
            showMessage('No database with that name.  Create it?  <a href="#" onclick="createDatabase();">Yes</a> | <a href="#" onclick="cancelLink();">No</a>', 'error', true);
        }
        else if (result === 'database') {

            showMessage('Successfully connected to that database.');
            showAndTell('#stepTwo', '#stepThree');
        }


        else {

            showMessage('Unknown error.  Please try again later.', 'error');

        }


    }
    }); 

}

PHP data handling script:

<?php

//Include rest class
require_once('../../classes/class_rest.php');

//Get variables
$task = $_POST['task'];

$database_server = $_POST['serverURL'];
$database_username = $_POST['serverUsername'];
$database_password = $_POST['serverPassword'];

$rest_name = $_POST['restName'];

$username = $_POST['username'];
$password = $_POST['password'];
$confPassword = $_POST['confirm'];
$emailAddress = $_POST['emailAddress'];

$api_name = $_POST['apiName'];

$database_name = $_POST['databaseName'];
$table_prefix = $_POST['tablePrefix'];

if ($task == 1){


    if($database_server == ''){
        print('nserver');
    }
    else if($database_username == ''){
        print('nserverusername');
    }
    else{
        connectSQL($database_server, $database_username, $database_password);
    }
}

else if ($task == 2){

    if($rest_name == ''){

        print('nrest');

    }
    else{

        databaseDoesExist($rest_name);

    }

}

else if ($task == 3){

    if($username == ''){

        print('nuser');
        die();

    }

    if($emailAddress == ''){

        print('nemail');
        die();

    }

    if(!$confPassword == $password){

        print('nconf');
        die();  
    }

    insertUser($username, $emailAddress, $password);

}

else if ($task == 4){

}

else if ($task == 5){

}

else if ($task == 6){

}


else if($task == 9){

    createInitialDatabase();

}

else if($task == 10){

    createConfigFile();

}
?>

Function in class_database.php:

//Validates sql information
function connectSQL($server, $username, $password){

    //Create sql connection
    $con = mysqli_connect($server, $username, $password);

    //Checks if connection was successful
    if (mysqli_connect_errno($con)){

        //Print 'badaccess' for ajax
        print('badaccess');

    }

    //Run if connection successful
    else{

        //Print 'success' for ajax
        print('success');

        //Adds session variables for other sql commands later on
        $_SESSION['server'] = $server;
        $_SESSION['username'] = $username;
        $_SESSION['password'] = $password;
    }

}
  • 写回答

3条回答 默认 最新

  • doudian6229 2013-08-09 18:03
    关注

    Few comments to your handling script: * make sure there's no white space before the opening <?php and as well, nothing after the trailing ?> which, btw, can be omitted as well (did you know?). * what about so called BOM in case of UTF-8 codified source codes? You may wanna choose an editor or editor setting that doesn't write BOM at the beginning of UTF files. * instead of, print('badaccess'); you might use die('badaccess'); – it will print the argument and stop the script execution. * at require_once (and directives alike) it's recommended to omit the parenthesis * consider rewriting long if...else statement dealing with $task to one switch().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败