2016-05-21 6 views
0

私はajaxコールを作成するたびに、常に2つの空のインデックス番号を持つ文字列を取得します。それはなぜですか、とにかくそれを修正するにはありますか?私はちょうどそれと一緒に暮らすと私はそれから文字をフェッチしたいときは、インデックス+ 2を使用する必要がありますか?私は間違って何かをやっている愚かな人ですか?Ajax returnTextには2つの空のインデックスがあります

私は実際のAjax関数を挿入していないため、このサイトでは機能しません。私が使用しているものは非常に面倒です。

function ajax(callback){ 
 
    
 
    /* Does it ajax stuff here in pure js*/ 
 
    
 
    
 
    /**/ 
 
    
 
    
 
    } 
 

 

 

 

 

 

 
/* Our ajax request */ 
 
ajax(function(responseText){ 
 

 
// This is where we do something with the string we got form the ajax 
 
    
 
// Let's say that the ajax returned a document with the text: sample text 
 
    
 
    
 
    
 
    // This will print out the whole string and it works perfectly 
 
    console.log(responseText); 
 

 
    
 
    // This SHOULD print out the first letter/char which is "s" 
 
    // But it dosn't by some reason!! 
 
    console.log(responseText[0]); 
 
    
 
    
 
    // But this does print out the first letter which is "s" by some reason 
 
console.log(responseText[2]); 
 
    
 
    
 
    // So this means that there must be 2 undefined/empty indexes of the returned string. 
 
    
 
    
 

 
});

+0

問題を再現し、ここでそれを共有する単純なバージョンに、あなたの目立たないコードを減らしてください。また、サーバーからの実際の応答と、それを生成する適切なコードを示してください。 – JAAulde

+0

@JAAuldeありがとう、私は将来の投稿でそれを行います。 –

答えて

1

あなたが反応して、余分な空白を持っているようですね。

String.prototype.trim()を使用して削除します。いっそ、常にこの

ajax(function(responseText) { 
    // clean outside whitespce 
    responseText = responseText.trim(); 


    console.log(responseText);  

    console.log('First char=',responseText[0]);  

    console.log('Third char=',responseText[2]); 

}); 
0

を試してみてくださいなどのタスクのためのJSONを使用アヤックス()関数から返されたあなたの応答では、いくつかの空白があるかもしれません。

responseText = responseText.trim(); 
関連する問題