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)
     }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题