weixin_33701251 2017-04-18 00:08 采纳率: 0%
浏览 111

将变量设置为ajax url

I'm trying to set ajax URL to variable res.

Variable res is a combination of different strings. You can have a look at the code.

HTML

    <form id="frm1">
    <input type="text" name="fname" value="" placeholder="Update Location">
    </form>
<button class="btn btn-default pull-right" onclick="loadWeather()"type="button">
 Search 
</button>

Here I'm trying to fetch the text in the form.

.js

window.onload = loadWeather();

var part = "http://api.openweathermap.org/data/2.5/weather?q=";
var a = encodeURI(part);
var b = document.getElementById("frm1");
var text = b.elements[0].value;
var urll = "&units=metric&appid=MYKEY";
var c = encodeURI(urll);

var res = a + text + c;

function loadWeather() {
    $.ajax({
        url: res,

When I check the value of res in console it's shown as undefined.

One more error is Cannot read property 'elements' of null at blog.js:7

All I want is that the final URL must be equal to something like this-

http://api.openweathermap.org/data/2.5/weather?q=FORMDATA&units=metric&appid=MYKEY

  • 写回答

1条回答 默认 最新

  • 普通网友 2017-04-18 03:51
    关注

    You have a logical error in your code. In the first line:

    window.onload = loadWeather();
    

    You are making a call to function loadWeather on page load, which means this function will be called immediately before any other javascript code. At this time you haven't assigned the res variable yet, which will be filled later after calling the function.

    You will have to call the function after variable assignment. For example, something like this will work:

     // window.onload = loadWeather();
     var part = "http://api.openweathermap.org/data/2.5/weather?q=";
     var a = encodeURI(part);
     var b = document.getElementById("frm1");
     var text = b.elements[0].value;
     var urll = "&units=metric&appid=MYKEY";
     var c = encodeURI(urll);
    
     var res = a + text + c;
     loadWeather()
     function loadWeather() {
         console.log(res)
     }
    
    评论

报告相同问题?